1
1
const std = @import ("std" );
2
+ const Allocator = std .mem .Allocator ;
2
3
const debug = std .debug ;
3
4
const assert = debug .assert ;
4
5
const testing = std .testing ;
5
6
6
- pub const Chirality = enum { lhs , rhs };
7
-
8
7
/// A very simple tree where every node is a tree.
9
8
/// This is primarily intended to be a backing data structure for more
10
9
/// sophisticated tree-based data structures with tuned insertion logic,
@@ -31,39 +30,20 @@ pub fn BinaryTree(comptime T: type) type {
31
30
/// Reverse the tree starting from this node in-place. Why would anyone
32
31
/// need this? Why does it come up in tech interviews?
33
32
/// This operation is O(N).
34
- ///
35
- /// Returns a pointer to self.
36
- pub fn reverse (self : * Self ) * Self {
33
+ pub fn reverse (self : * Self ) void {
37
34
const temp = self .lhs ;
38
35
39
36
self .lhs = self .rhs ;
40
37
self .rhs = temp ;
41
38
42
- if (self .lhs ) | lhs | _ = lhs .reverse ();
43
- if (self .rhs ) | rhs | _ = rhs .reverse ();
44
-
45
- return self ;
46
- }
47
-
48
- /// Assigns a node to one of the sides of this node.
49
- ///
50
- /// Returns a pointer to subtree.
51
- pub fn assign (self : * Self , side : Chirality , subtree : * Self ) * Self {
52
- switch (side ) {
53
- .lhs = > self .lhs = subtree ,
54
- .rhs = > self .rhs = subtree ,
55
- }
56
-
57
- return subtree ;
39
+ if (self .lhs ) | lhs | lhs .reverse ();
40
+ if (self .rhs ) | rhs | rhs .reverse ();
58
41
}
59
42
60
43
/// Sets both lhs and rhs to null.
61
- ///
62
- /// Returns a pointer to self.
63
- pub fn reset (self : * Self ) * Self {
44
+ pub fn prune (self : * Self ) void {
64
45
self .lhs = null ;
65
46
self .rhs = null ;
66
- return self ;
67
47
}
68
48
};
69
49
}
@@ -177,7 +157,8 @@ test "((5 - 4) + (0 + 2)) + ((6 - 2) + (2 + 3))" {
177
157
// / \ / \ / \ / \
178
158
// 3 2 2 6 2 0 4 5
179
159
180
- var zero = negativeSix .reverse ();
181
- try testing .expectEqual (@as (i32 , 0 ), Math .resolve (zero ));
160
+ negativeSix .reverse ();
161
+ var zero = negativeSix ;
162
+ try testing .expectEqual (@as (i32 , 0 ), Math .resolve (& zero ));
182
163
try testing .expectEqual (@as (usize , 15 ), zero .count ());
183
164
}
0 commit comments