Skip to content

Commit e8718ef

Browse files
committed
Subtree of Another Tree
1 parent ae82cb1 commit e8718ef

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,4 @@
3333
29. Maximum Depth of Binary Tree - (https://leetcode.com/problems/maximum-depth-of-binary-tree/)
3434
30. Binary Tree Maximum Path Sum - (https://leetcode.com/problems/binary-tree-maximum-path-sum/) (H)
3535
31. Binary Tree Level Order Traversal - (https://leetcode.com/problems/binary-tree-level-order-traversal/) (M)
36+
32. Subtree of Another Tree - (https://leetcode.com/problems/subtree-of-another-tree/) (E)

subtree-of-another-tree.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/***Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
2+
3+
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself. */
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @param {TreeNode} subRoot
15+
* @return {boolean}
16+
*/
17+
var isSubtree = function(root, subRoot) {
18+
if (!subRoot) {
19+
return true;
20+
}
21+
22+
if (!root) {
23+
return false;
24+
}
25+
26+
if (isSameTree(root, subRoot)) {
27+
return true;
28+
}
29+
30+
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
31+
};
32+
33+
function isSameTree(p, q) {
34+
if (!p && !q) {
35+
return true;
36+
}
37+
38+
if (!p || !q || p.val !== q.val) {
39+
return false;
40+
}
41+
42+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
43+
}

0 commit comments

Comments
 (0)