Why is inorder and preorder traversal useful for creating an algorithm to decide if T2 is a subtree of T1

前端 未结 3 1397
深忆病人
深忆病人 2021-02-08 16:35

I\'m looking at an interview book and the question is:

You have two very large binary trees: T1, with millions of nodes, and T2

3条回答
  •  隐瞒了意图╮
    2021-02-08 17:10

    Important assumption is that the tree has unique keys.

    Now, note that preorder-traversal-string and inorder-traversal-string uniquely identify a binary tree.

    Scatch of the proof:

    Let T be a tree.

    • First object in preorder-traversal-string(T) is the root.
    • Find it in the in the inorder-traversal-string(T) - everything on left of that element is your left subtree L, let's call this substring inorder-traversal-string(L). Everything on right is your right subtree R.

    Now, let's focus on the left subtree L.

    • Clearly all subtrees are separated (they don't mix) in both strings. They are represented as consecutive objects. The only problem is that a priori we don't know where preorder-traversal-string(L) ends in preorder-traversal-string(T).
    • Note that strings inorder-traversal-string(L) and preorder-traversal-string(L) have the same length. This gives as the place where to cut.
    • Now you have a subtree described as substrings inorder-traversal-string(L) and preorder-traversal-string(L) so you can repeat the procedure till the end.

    Following those steps (inefficient but it is just for the proof) for all subtrees you will uniquely build the tree.

    Thus, all subtrees of T1 are described uniquely by corresponding inorder-traversal-string and preorder-traversal-string.

提交回复
热议问题