• 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
  • 相关阅读:
    或得最新的采购单号并改变为定长
    javaScript学习之路(1)词法结构
    如何让IE下载时下载内容自动跳转到迅雷等下载软件中
    简单的数据库查询操作
    1.1软件工程概述之软件危机
    SQL基础(巧记范式)
    给程序员的五点建议--如何成为编程高手并以此创业
    License控制解决方案
    MVC+三层+ASP.NET简单登录验证
    我曾七次鄙视自己的灵魂
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12963537.html
Copyright © 2020-2023  润新知