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 2Given tree t:
4 / \ 1 2Return 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 / 0Given tree t:
4 / \ 1 2Return false.
题目是判断二叉树t是不是二叉树s的子树。
class Solution {
public:
bool isSameTree(TreeNode* s, TreeNode* t){
if(!s&&!t)return true;//两个都未空,说明到叶子节点
else if(!s||!t)return false;//只有一个节点为空,不相等
else return s->val==t->val&&isSameTree(s->left,t->left)&&isSameTree(s->right,t->right);
}
bool isSubtree(TreeNode* s, TreeNode* t) {
if(!s)return false;
if(isSameTree(s,t))return true;
else return isSubtree(s->left,t)||isSubtree(s->right,t);
}
};