572. Subtree of Another Tree 572.另一棵树的子树

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.

 

 

复习时还不会的地方:再加一组子函数
而且这道题独特的地方是判断isSameTree(s.left, t)|| isSameTree(s.right, t)

 

 

怎么顾及到别的根节点啊?
return isSubtree(s.left, t) || isSubtree(s.right, t);
既然是子树就只需要子树跟另一棵树一样就行了,反正只是递归中的一部分
这tm也太抽象了吧!

 

好吧,其实isSameTree只是大的递归中的一个小递归罢了。递归是可以嵌套的

 

 

主函数:isSameTree(s.left, t) && isSameTree(s.right, t);
是这样吧?虽然我也不懂为啥。是的,而且要用到嵌套递归

 

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        //特殊情况,还是得有的
        if (s == null) return false;
        
        //直接是相同的树
        if(isSameTree(s, t)) return true;
            
        //子树的情况
        return isSubtree(s.left, t) || isSubtree(s.right, t);
    }
    
    public boolean isSameTree(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 isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
    }
}
View Code

 

posted @ 2020-05-26 09:35  苗妙苗  阅读(99)  评论(0编辑  收藏  举报