标签:roots == 题目 函数 算法 lang 节点 code return
有两个不同大小的二叉树: T1有上百万的节点; T2有好几百的节点。请设计一种算法,判定T2是否为T1的子树。
若根节点相同,则直接返回true。
若根节点不同,则递归比较T1的左、右子树和T2。
/**
* 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;
}
}
标签:roots == 题目 函数 算法 lang 节点 code return
原文地址:https://www.cnblogs.com/Akatsuki-Sanjou/p/12723164.html