Skip to content

Commit 60acd07

Browse files
committed
Add solution #572
1 parent 3101964 commit 60acd07

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,7 @@
450450
565|[Array Nesting](./0565-array-nesting.js)|Medium|
451451
566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy|
452452
567|[Permutation in String](./0567-permutation-in-string.js)|Medium|
453+
572|[Subtree of Another Tree](./0572-subtree-of-another-tree.js)|Easy|
453454
575|[Distribute Candies](./0575-distribute-candies.js)|Easy|
454455
589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy|
455456
594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy|
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 572. Subtree of Another Tree
3+
* https://leetcode.com/problems/subtree-of-another-tree/
4+
* Difficulty: Easy
5+
*
6+
* Given the roots of two binary trees root and subRoot, return true if there is a subtree of
7+
* root with the same structure and node values of subRoot and false otherwise.
8+
*
9+
* A subtree of a binary tree tree is a tree that consists of a node in tree and all of this
10+
* node's descendants. The tree tree could also be considered as a subtree of itself.
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* function TreeNode(val, left, right) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.left = (left===undefined ? null : left)
18+
* this.right = (right===undefined ? null : right)
19+
* }
20+
*/
21+
/**
22+
* @param {TreeNode} root
23+
* @param {TreeNode} subRoot
24+
* @return {boolean}
25+
*/
26+
var isSubtree = function(root, subRoot) {
27+
return traverse(root).includes(traverse(subRoot));
28+
function traverse(node) {
29+
return !node ? '#' : `,${node.val},${traverse(node.left)},${traverse(node.right)}`;
30+
}
31+
};

0 commit comments

Comments
 (0)