Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t hasexactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants.The tree s could also be considered as a subtree of itself.
Divide and Conquer
Time Complexity
这题最差的时间复杂度是O(mn),m,n分别代表大树和subtree的个数。因为isSame的时间复杂度是O(N),最差的情况相当于对于这个大树的每个点都要做一次subtree个数的isSame的搜索,所以是O(N^2)
Space Complexity
没有额外空间,如果要算上栈的空间是 O(2logn)
思路
对整个树前序遍历,对于每一个点做一次isSameTree的判断。如果subtree为空,是一种特殊情况,符合要求
代码
public boolean isSubtree(TreeNode s, TreeNode t) {
if(t == null) return true;
if(s == null) return false;
if(isSameTree(s, t)){
return true;
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
private boolean isSameTree(TreeNode a, TreeNode b){
if(a == null && b == null) return true;
if(a == null || b == null) return false;
if(a.val != b.val) return false;
return isSameTree(a.left, b.left) && isSameTree(a.right, b.right);
}
优化
这题还可以优化成O(N)的时间复杂度
可以用Inorder加上preorder的方法遍历两棵树,把这样遍历的顺序加入数组,比如inorderTree[], preorderTree[], inorderSubTree[], preOrderSubTree[]
之后只要再遍历数组,看一下preorderTree[]中有没有subarray是preOrderSubTree[] && inorderTree[]中有没有subarray是inorderSubTree[]
为什么要用inorder和preorder可以参考
http://www.geeksforgeeks.org/...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。