-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubtree_of_another_tree_test.dart
59 lines (46 loc) · 1.17 KB
/
subtree_of_another_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
59
import 'dart:collection';
import 'package:test/test.dart';
// See same_tree_test for other solutions for comparing two trees.
bool subtree(Node a, Node b) {
final stack = DoubleLinkedQueue<Node>()..add(a);
while (stack.isNotEmpty) {
final node = stack.pop();
if (node == b) return true;
if (node.left != null) stack.add(node.left!);
if (node.right != null) stack.add(node.right!);
}
return false;
}
extension MiniStack<E> on Queue<E> {
void push(E value) => addLast(value);
E pop() => removeLast();
}
class Node {
const Node(this.value, [this.left, this.right]);
final int value;
final Node? left;
final Node? right;
@override
bool operator ==(Object o) =>
o is Node && o.value == value && o.left == left && o.right == right;
@override
int get hashCode => Object.hash(value, left, right);
}
void main() {
test('leetcode', () {
expect(
subtree(
Node(3, Node(4, Node(1), Node(2)), Node(5)),
Node(4, Node(1), Node(2)),
),
true,
);
expect(
subtree(
Node(3, Node(4, Node(1), Node(2, Node(0))), Node(5)),
Node(4, Node(1), Node(2)),
),
false,
);
});
}