原文链接 [每日 LeetCode] 572. Subtree of Another Tree
Description:
Given two non-empty binary trees s and t , check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
思路:本题要求判断一个树是不是另一棵树的子树,要求不能是中间的树,只能是从叶子结点开始。可以使用[每日 LeetCode] 100. Same Tree 代码,对原始树遍历,如果是同一棵树就返回 true,否则返回 false。
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(!s)
return false;
if (isSameTree(s,t))
return true;
return isSubtree(s->left,t) || isSubtree(s->right,t);
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == NULL || q == NULL)
return (p == q);
return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};
运行时间:32ms
运行内存:21.2M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于