mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
27 lines
927 B
Markdown
27 lines
927 B
Markdown
# [572. Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
|
||
|
||
# 思路
|
||
让我们求一个数是否是另一个树的子树,从题目中的第二个例子中可以看出,中间某个部分的不能算是子树。如果从s的某个结点开始,跟t的所有结构都一样就可以了,所以问题转换为判断两树是否相等,即[100. Same Tree](100.%20Same%20Tree.md)。
|
||
|
||
|
||
# C++
|
||
|
||
``` C++
|
||
class Solution {
|
||
private:
|
||
bool isSameTree(TreeNode* t1, TreeNode* t2){
|
||
if(!t1 || !t2) return (!t1 && !t2);
|
||
return (t1 -> val == t2 -> val) && \
|
||
isSameTree(t1 -> left, t2 -> left) && \
|
||
isSameTree(t1 -> right, t2 -> right);
|
||
}
|
||
public:
|
||
bool isSubtree(TreeNode* s, TreeNode* t) {
|
||
if(!s) return t == NULL;
|
||
if(!t) return true;
|
||
return isSameTree(s, t) || isSubtree(s -> left, t) || isSubtree(s -> right, t);
|
||
}
|
||
};
|
||
```
|
||
|