Skip to content

Commit faf6301

Browse files
committed
feat: subtree-of-another-tree
1 parent 6555c38 commit faf6301

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// n: number of nodes in root, m: number of nodes in subroot
2+
// Time complexity: O(n*m)
3+
// Space complexity: O(n)
4+
5+
class _Queue {
6+
constructor() {
7+
this.q = [];
8+
this.front = 0;
9+
this.rear = 0;
10+
}
11+
12+
isEmpty() {
13+
return this.front === this.rear;
14+
}
15+
16+
push(value) {
17+
this.q.push(value);
18+
this.rear++;
19+
}
20+
21+
shift() {
22+
const rv = this.q[this.front];
23+
delete this.q[this.front++];
24+
return rv;
25+
}
26+
}
27+
/**
28+
* Definition for a binary tree node.
29+
* function TreeNode(val, left, right) {
30+
* this.val = (val===undefined ? 0 : val)
31+
* this.left = (left===undefined ? null : left)
32+
* this.right = (right===undefined ? null : right)
33+
* }
34+
*/
35+
/**
36+
* @param {TreeNode} root
37+
* @param {TreeNode} subRoot
38+
* @return {boolean}
39+
*/
40+
var isSubtree = function (root, subRoot) {
41+
const check = (root, subRoot) => {
42+
const q = new _Queue();
43+
q.push([root, subRoot]);
44+
45+
while (!q.isEmpty()) {
46+
const [node, subNode] = q.shift();
47+
48+
if (node.val !== subNode.val) {
49+
return false;
50+
}
51+
52+
if ((node.left && !subNode.left) || (!node.left && subNode.left)) {
53+
return false;
54+
}
55+
56+
if ((node.right && !subNode.right) || (!node.right && subNode.right)) {
57+
return false;
58+
}
59+
60+
if (node.left && subNode.left) {
61+
q.push([node.left, subNode.left]);
62+
}
63+
64+
if (node.right && subNode.right) {
65+
q.push([node.right, subNode.right]);
66+
}
67+
}
68+
69+
return true;
70+
};
71+
72+
const q = new _Queue();
73+
q.push(root);
74+
75+
while (!q.isEmpty()) {
76+
const current = q.shift();
77+
78+
if (check(current, subRoot)) {
79+
return true;
80+
}
81+
82+
if (current.left) {
83+
q.push(current.left);
84+
}
85+
86+
if (current.right) {
87+
q.push(current.right);
88+
}
89+
}
90+
91+
return false;
92+
};

0 commit comments

Comments
 (0)