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

前端 未结 3 1403
深忆病人
深忆病人 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 16:56

    Here is a counter-example to the method.

    Consider the tree T1:

      B
     / \
    A   D
       / \
      C   E
           \
            F
    

    And the sub-tree T2:

      D
     / \
    C   E
    

    The relevant traversals are:

    • T1 pre-order: BADCEF
    • T2 pre-order: DCE
    • T1 in-order: ABCDEF
    • T2 in-order: CDE

    While DCE is in BADCEF and CDE is in ABCDEF, T2 is not actually a sub-tree of T1. The author's definition of sub-tree must have been different or it was just a mistake.

    Related question: Determine if a binary tree is subtree of another binary tree using pre-order and in-order strings

提交回复
热议问题