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) {
if (T1 == null && T2 == null){
return true;
}else if (T1 == null){
return false;
}else if (T2 == null){
return true;
}
//actually here it still looks like divide & conquer in that there are three possibilities that is subtree: the root itself, the left child and right child
//and if the root itself is a subtree, then it must be the same tree
return isSameTree(T1, T2) || isSubtree(T1.left, T2) || isSubtree(T1.right, T2);
}
public boolean isSameTree(TreeNode p, TreeNode q){
if (p == null && q == null){
return true;
}else if (p == null || q == null){
return false;
}else if (p.val != q.val){
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。