【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.

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.

题目是判断二叉树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);
    }
};

猜你喜欢

转载自blog.csdn.net/a342500329a/article/details/77689484
今日推荐