Leetcode 572. Subtree of Another Tree
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.
题目大意:
给定两棵非空二叉树s和t,判断t是不是s的完全子树。
解题思路:
对s以每一个结点视为根结点作同样的操作,判断从该节点开始是否能遍历出和t一样的结构。由于重复做同样的操作,则可用递归完成。
代码:
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(!s)
return false;
if(isSame(s, t))
return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool isSame(TreeNode *s, TreeNode *t){
if(!s && !t)
return true;
else if(!s || !t)
return false;
else if(s->val != t->val)
return false;
return isSame(s->left, t->left) && isSame(s->right, t->right);
}
};
本文探讨了LeetCode上的经典题目——检查二叉树子树问题,介绍了如何通过递归算法判断一棵二叉树是否为另一棵二叉树的子树。文章详细解释了解题思路,并提供了具体的C++代码实现。
1955

被折叠的 条评论
为什么被折叠?



