zoukankan      html  css  js  c++  java
  • LintCode Subtree

    原题链接在这里:http://www.lintcode.com/en/problem/subtree/

    You have two every large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree ofT1.

    Example

    T2 is a subtree of T1 in the following case:

           1                3
          /               / 
    T1 = 2   3      T2 =  4
            /
           4
    

    T2 isn't a subtree of T1 in the following case:

           1               3
          /                
    T1 = 2   3       T2 =    4
            /
           4
    
    Note

    A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

    Time Complexity: O(m*n), m是T1的node数, n 是T2的node 数. Space: O(logm). isSame用logn, isSubtree用logm.

    AC Java:

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param T1, T2: The roots of binary tree.
    15      * @return: True if T2 is a subtree of T1, or false.
    16      */
    17     public boolean isSubtree(TreeNode T1, TreeNode T2) {
    18         // write your code here
    19         if(T2 == null){
    20             return true;
    21         }
    22         if(T1 == null){
    23             return false;
    24         }
    25         return isSame(T1,T2) || isSubtree(T1.left, T2) || isSubtree(T1.right, T2);
    26     }
    27     
    28     private boolean isSame(TreeNode T1, TreeNode T2){
    29         if(T1 == null && T2 == null){
    30             return true;
    31         }
    32         if(T1 == null || T2 == null){
    33             return false;
    34         }
    35         if(T1.val != T2.val){
    36             return false;
    37         }
    38         return isSame(T1.left, T2.left) && isSame(T1.right, T2.right);
    39     }
    40 }
  • 相关阅读:
    C# 从服务器下载文件
    不能使用联机NuGet 程序包
    NPOI之Excel——合并单元格、设置样式、输入公式
    jquery hover事件中 fadeIn和fadeOut 效果不能及时停止
    UVA 10519 !! Really Strange !!
    UVA 10359 Tiling
    UVA 10940 Throwing cards away II
    UVA 10079 Pizze Cutting
    UVA 763 Fibinary Numbers
    UVA 10229 Modular Fibonacci
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5188429.html
Copyright © 2011-2022 走看看