-
Notifications
You must be signed in to change notification settings - Fork 2
/
leetcode-572-Subtree of Another Tree.js
46 lines (46 loc) · 1.19 KB
/
leetcode-572-Subtree of Another Tree.js
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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} s
* @param {TreeNode} t
* @return {boolean}
*/
var isSubtree = function(s, t) {
if (!s) {
return false;
}
const compare = (p, q) => {
if (!p && !q) {
return true;
} else if ((!p && q) || (p && !q) || (p.val !== q.val)) {
return false;
}
return compare(p.left, q.left) && compare(p.right, q.right);
}
let queue = [s];
const map = (node) => {
if (!node) {
return;
}
while(queue.length) {
let tempQueue = [];
for (let i = 0; i < queue.length; i++) {
let item = queue[i];
if (compare(item, t)) {
return true;
}
item.left && tempQueue.push(item.left);
item.right && tempQueue.push(item.right);
}
queue = tempQueue;
}
return false;
}
return map(s);
};