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);
}
};