Last updated
Was this helpful?
Last updated
Was this helpful?
You have two every large binary trees:T1
, with millions of nodes, andT2
, with hundreds of nodes. Create an algorithm to decide ifT2
is a subtree ofT1
.
A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.
Example
T2 is a subtree of T1 in the following case:
T2 isn't a subtree of T1 in the following case:
这题来自ctci 4.10。如果两棵树都不大的话,我们可以通过判断T2的preorder+null是否T1的perorder+null序列的子序列来判断是否subtree。会花费O(n + m)的空间和时间。但如果T1非常大的话,我们可以先从T1里找T2root的值,找到了再判断是否subtree。这个方法会花O(logn + logm)的空间,平均时间是O(n + km),k是T1里T2root值的个数。worse case时间会变成O(nm)。