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
这里有两个重点:
如果
T2
是空树,总为true
;如果T1
为空树,总为false
。那么哪个优先级更高,就要更早一点讨论。所以if (T2 == null)
要放在if (T1 == null)
前面。用到递归,就要先讨论更小范围的极端情况,再走递归语句。所以先讨论全等树
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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。