-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubtree-of-another-tree.js
More file actions
45 lines (41 loc) · 1.01 KB
/
subtree-of-another-tree.js
File metadata and controls
45 lines (41 loc) · 1.01 KB
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
/**
* 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} root
* @param {TreeNode} subRoot
* @return {boolean}
*/
var isSubtree = function (root, subRoot) {
// 一棵树是另一棵树的子树,说明:
// (1) 要么两棵树相等
// (2) 要么subRoot是root左树的子树
// (3) 要么subRoot是root右树的子树
if (!root) {
return false;
}
const isSame = isSameTree(root, subRoot);
return (
isSame || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
);
};
// 验证是不是同一棵树
function isSameTree(root1, root2) {
if (!root1 && !root2) {
return true;
}
if (!root2 || !root1) {
return false;
}
if (root2.val !== root1.val) {
return false;
}
return (
isSameTree(root1.left, root2.left) && isSameTree(root1.right, root2.right)
);
}