mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2026-08-31 12:14:44 +08:00
add 572
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
# [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);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user