[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

相關文章
相關標籤/搜索