Subtree
Description
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.
Notice
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.
实现思路
基于树的问题,我们可以将其分解为一个个小问题进行递归求解。
对于某个状态下的节点T1,T2,假设前面的节点都不满足“子树”关系,判断当前状态下,以T1为根的节点是否和T2构成子树关系,我们可以根据下面步骤判断:
1. 如果T1为空,T2还有节点,肯定不是子树关系
2. 如果T2空了,无论T1存在与否,必为子树关系
3. 如果T2往后的节点都和T1对应部分相等,则为子树关系
4. 如果前面都不满足,则找不到以T1为根的节点和T2满足子树关系。故找以T1左子树为根的节点和T1右子树为根的节点是否和T2满足字数关系
对于第3步,我们需要判断T2及其子节点是否和T1及其相应部分子节点是否全等,可以简单地做递归遍历判断,具体看以下实现:
/**
* 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, T2: The roots of binary tree.
* @return: True if T2 is a subtree of T1, or false.
*/
public boolean isSubtree(TreeNode T1, TreeNode T2) {
// write your code here
if(T2 != null && T1 == null){
return false;
}else if(T2 == null){
return true;
}
if(isEqual(T1, T2)){
return true;
}
return isSubtree(T1.left,T2) || isSubtree(T1.right,T2);
}
public boolean isEqual(TreeNode T1, TreeNode T2){
if(T2 == null && T1 == null){
return true;
}else if(T2 != null && T1 != null){
if(T1.val == T2.val && isEqual(T1.left,T2.left) && isEqual(T1.right,T2.right)){
return true;
}
}
return false;
}
}