zoukankan      html  css  js  c++  java
  • 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.

     

    怎么顾及到别的根节点啊?
    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
  • 相关阅读:
    搭建聊天机器人Bot Framework
    UsernamePasswordAuthenticationToken
    在JavaWeb项目中URL中字符串加密解密方案
    python自定义库文件路径
    difference between collection and association mapping in mybatis 3
    statpot:使用mongo+bootstrap+highcharts做统计报表
    Android仿微信SlideView聊天列表滑动删除效果
    Android Studio 运行、编译卡死的解决办法
    Android wear
    android实现json数据的解析和把数据转换成json格式的字符串
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12963537.html
Copyright © 2011-2022 走看看