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.
Analysis:
实现方案:递归+二叉树先序遍历
思路1:
递归,先写递归出口,当s == NULL且t == NULL,返回true,当s->val == t->val时,继续分别递归判断左右子树,只有当左右子树都相同,返回true,否则跳出(注意:跳出如何处理),继续在左子树和右子树分别和根节点t判断;
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
return isSubtreeFlag(s, t, false);
}
bool isSubtreeFlag(TreeNode* s, TreeNode* t, bool flag) {
if (s == NULL && t == NULL)
return true;
if (s == NULL || t == NULL)
return false;
if (s->val == t->val) {
if (isSubtreeFlag(s->left, t->left, true) && isSubtreeFlag(s->right, t->right, true))
return true;
}
if (flag)
return false;
if (!isSubtreeFlag(s->left, t, false))
return isSubtreeFlag(s->right, t, false);
return true;
}
};
思路2:
还是递归,加一个方法判断以根节点的树是否相同,思路2更好
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if (s == NULL)
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 == NULL && t == NULL)
return true;
if (s == NULL || t == NULL)
return false;
if (s->val != t->val)
return false;
return isSame(s->left, t->left) && isSame(s->right, t->right);
}
};