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

前端 未结 3 1561
执笔经年
执笔经年 2021-02-08 16:45

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:50

    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

提交回复
热议问题