【LeetCode】572. Subtree of Another Tree

来源:互联网 发布:淘宝led散热片 编辑:程序博客网 时间:2024/06/05 01:18

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