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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值