我正在看一本面试书,问题是:
You have two very large binary trees:
T1
, with millions of nodes, andT2
, with hundreds of nodes. Create an algorithm to decide ifT2
is a subtree ofT1
.
作者提到这是一个可能的解决方案:
Note that the problem here specifies that
T1
has millions of nodes—this means that we should be careful of how much space we use. Let’s say, for example,T1
has 10 million nodes—this means that the data alone is about40 mb
. We could create a string representing the inorder and preorder traversals. IfT2
’s preorder traversal is a substring ofT1
’s preorder traversal, andT2
’s inorder traversal is a substring ofT1
’s inorder traversal, thenT2
is a substring ofT1
.
如果这些都是真的,我不太确定背后的逻辑:
-
T2-preorder-traversal-string
是T1-preorder-traversal-string
的子串 -
T2-inorder-traversal-string
是T1-inorder-traversal-string
的子串
那个T2
必须是 T1
的子字符串(虽然我假设作者指的是子树) .我能得到这个逻辑的解释吗?
编辑:用户 BartoszMarcinkowski 提出了一个很好的观点。假设两棵树都没有重复的节点。
最佳答案
我认为这不是真的。考虑:
T2:
2
/ \
1 3
inorder 123 preorder 213
和
T1:
0
/ \
3 3
/ \
1 1
/ \
0 2
inorder 0123103 preorder 0310213
123
是0123103
的子串,213
是0310213
的子串,但T2不是T1的子树.
关于algorithm - 为什么中序和先序遍历对于创建算法来确定 T2 是否是 T1 的子树很有用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238899/