-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary_search_tree.zig
More file actions
89 lines (80 loc) · 2.52 KB
/
binary_search_tree.zig
File metadata and controls
89 lines (80 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const std = @import("std");
const expect = std.testing.expect;
fn Node(comptime T: type) type {
return struct {
value: T,
parent: ?*Node(T) = null,
left: ?*Node(T) = null,
right: ?*Node(T) = null,
};
}
/// References: Introduction to algorithms / Thomas H. Cormen...[et al.]. -3rd ed.
fn Tree(comptime T: type) type {
return struct {
root: ?*Node(T) = null,
//Exercise: why does the worst case performance of binary search trees
//`O(n)` differ from binary search on sorted arrays `O(log n)`?
pub fn search(node: ?*Node(T), value: T) ?*Node(T) {
if (node == null or node.?.value == value) {
return node;
}
if (value < node.?.value) {
return search(node.?.left, value);
} else {
return search(node.?.right, value);
}
}
//Based on the insertions can you see how this data structure relates
//to sorting? Hint: try outputting the resulting tree
pub fn insert(self: *Tree(T), z: *Node(T)) void {
var y: ?*Node(T) = null;
var x = self.root;
while (x) |node| {
y = node;
if (z.value < node.value) {
x = node.left;
} else {
x = node.right;
}
}
z.parent = y;
if (y == null) {
self.root = z;
} else if (z.value < y.?.value) {
y.?.left = z;
} else {
y.?.right = z;
}
}
};
}
pub fn main() !void {}
test "search empty tree" {
var tree = Tree(i32){};
var result = Tree(i32).search(tree.root, 3);
try expect(result == null);
}
test "search an existing element" {
var tree = Tree(i32){};
var node = Node(i32){ .value = 3 };
tree.insert(&node);
var result = Tree(i32).search(tree.root, 3);
try expect(result.? == &node);
}
test "search non-existent element" {
var tree = Tree(i32){};
var node = Node(i32){ .value = 3 };
tree.insert(&node);
var result = Tree(i32).search(tree.root, 4);
try expect(result == null);
}
test "search for an element with multiple nodes" {
var tree = Tree(i32){};
const values = [_]i32{ 15, 18, 17, 6, 7, 20, 3, 13, 2, 4, 9 };
for (values) |v| {
var node = Node(i32){ .value = v };
tree.insert(&node);
}
var result = Tree(i32).search(tree.root, 9);
try expect(result.?.value == 9);
}