[LeetCode] Subtree of Another Tree

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.node

Divide and Conquer

Time Complexity
这题最差的时间复杂度是O(mn),m,n分别表明大树和subtree的个数。由于isSame的时间复杂度是O(N),最差的状况至关于对于这个大树的每一个点都要作一次subtree个数的isSame的搜索,因此是O(N^2)数组

Space Complexity
没有额外空间,若是要算上栈的空间是 O(2logn)ide

思路

对整个树前序遍历,对于每个点作一次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[]this

为何要用inorder和preorder能够参考
http://www.geeksforgeeks.org/...code

相关文章
相关标签/搜索