【递归】子树

dushine00 2020-04-17

题目要求

有两个不同大小的二叉树: T1有上百万的节点; T2有好几百的节点。请设计一种算法,判定T2是否为T1的子树。

思路解析

若根节点相同,则直接返回true。
若根节点不同,则递归比较T1的左、右子树和T2。

要注意的点

  • isEqual()函数的实现。
  • 对于T1、T2是空值情况的具体判断。

Java实现

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param T1: The roots of binary tree T1.
     * @param T2: The roots of binary tree T2.
     * @return: True if T2 is a subtree of T1, or false.
     */
    public boolean isEqual(TreeNode T1, TreeNode T2) {
        if(T1 == null || T2 == null) {
            return T1 == T2;
        }
        
        if(T1.val != T2.val) {
            return false;
        }
        
        return isEqual(T1.left, T2.left) && isEqual(T1.right, T2.right);
    }
    
    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;
    }
}

相关推荐