LeetCode/solutions/572. Subtree of Another Tree.md
2020-02-04 17:53:32 +08:00

27 lines
927 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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);
}
};
```