Skip to content

Commit d4b9ee0

Browse files
committed
add 572
1 parent f3b5d80 commit d4b9ee0

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
284284
| 532 |[K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/532.%20K-diff%20Pairs%20in%20an%20Array.md)|Easy| |
285285
| 561 |[Array Partition I](https://leetcode.com/problems/array-partition-i)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/561.%20Array%20Partition%20I.md)|Easy| |
286286
| 566 |[Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/566.%20Reshape%20the%20Matrix.md)|Easy| |
287+
| 572 |[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)|[C++](solutions/572.%20Subtree%20of%20Another%20Tree.md)|Easy| |
287288
| 581 |[Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/581.%20Shortest%20Unsorted%20Continuous%20Subarray.md)|Easy| |
288289
| 605 |[Can Place Flowers](https://leetcode.com/problems/can-place-flowers)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/605.%20Can%20Place%20Flowers.md)|Easy| |
289290
| 628 |[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/628.%20Maximum%20Product%20of%20Three%20Numbers.md)|Easy| |
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# [572. Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
2+
3+
# 思路
4+
让我们求一个数是否是另一个树的子树,从题目中的第二个例子中可以看出,中间某个部分的不能算是子树。如果从s的某个结点开始,跟t的所有结构都一样就可以了,所以问题转换为判断两树是否相等,即[100. Same Tree](100.%20Same%20Tree.md)
5+
6+
7+
# C++
8+
9+
``` C++
10+
class Solution {
11+
private:
12+
bool isSameTree(TreeNode* t1, TreeNode* t2){
13+
if(!t1 || !t2) return (!t1 && !t2);
14+
return (t1 -> val == t2 -> val) && \
15+
isSameTree(t1 -> left, t2 -> left) && \
16+
isSameTree(t1 -> right, t2 -> right);
17+
}
18+
public:
19+
bool isSubtree(TreeNode* s, TreeNode* t) {
20+
if(!s) return t == NULL;
21+
if(!t) return true;
22+
return isSameTree(s, t) || isSubtree(s -> left, t) || isSubtree(s -> right, t);
23+
}
24+
};
25+
```
26+

0 commit comments

Comments
 (0)