-
Notifications
You must be signed in to change notification settings - Fork 0
/
invert_binary_tree_test.dart
58 lines (51 loc) · 1.22 KB
/
invert_binary_tree_test.dart
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
import 'package:test/test.dart';
// Recursive solution, preorder traversal (postorder would also work).
TreeNode? invertTreeR(TreeNode? node) {
if (node == null) return null;
node.swapChildren();
invertTreeR(node.left);
invertTreeR(node.right);
return node;
}
extension on TreeNode {
void swapChildren() {
final t = left;
left = right;
right = t;
}
}
class TreeNode {
TreeNode(this.value, [this.left, this.right]);
int value;
TreeNode? left;
TreeNode? right;
// Used only for testing
@override
bool operator ==(Object o) =>
o is TreeNode && o.value == value && o.left == left && o.right == right;
@override
int get hashCode => Object.hash(value, left, right);
}
void main() {
test('LC Example 1', () {
expect(
invertTreeR(
TreeNode(
4,
TreeNode(2, TreeNode(1), TreeNode(3)),
TreeNode(7, TreeNode(6), TreeNode(9)),
),
),
TreeNode(
4,
TreeNode(7, TreeNode(9), TreeNode(6)),
TreeNode(2, TreeNode(3), TreeNode(1)),
),
);
expect(
invertTreeR(TreeNode(2, TreeNode(1), TreeNode(3))),
TreeNode(2, TreeNode(3), TreeNode(1)),
);
expect(invertTreeR(null), null);
});
}