Problem

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 of T1.

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

这里有两个重点:

  1. 如果T2是空树,总为true;如果T1为空树,总为false。那么哪个优先级更高,就要更早一点讨论。所以if (T2 == null)要放在if (T1 == null)前面。

  2. 用到递归,就要先讨论更小范围的极端情况,再走递归语句。所以先讨论全等树isEqual(T1, T2),再用||语句递归T1的左右子树。

Solution

public class Solution {
    public boolean isSubtree(TreeNode T1, TreeNode T2) {
        if (T2 == null) return true;
        if (T1 == null) return false;
        if (isEqual(T1, T2)) return true;
        if (isSubtree(T1.left, T2) || isSubtree(T1.right, T2)) return true;
        return false;
    }
    public boolean isEqual(TreeNode T1, TreeNode T2) {
        if (T1 == null || T2 == null) return T1 == T2;
        if (T1.val != T2.val) return false;
        if (isEqual(T1.left, T2.left) && isEqual(T1.right, T2.right)) return true;
        return false;
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论