checking subtrees using preorder and inorder strings

后端 未结 4 715
别跟我提以往
别跟我提以往 2020-12-10 16:16

A book I\'m reading claims that one way to check whether a binary tree B is a subtree of a binary tree A is to build the inorder and <

相关标签:
4条回答
  • 2020-12-10 17:02

    Consider the two two node trees with A and B as nodes. Tree one has B as root and A as left child. Tree two has A as root and B as right child. The inorder traversals match but the trees differ.

    0 讨论(0)
  • 2020-12-10 17:12

    I think you need both if the tree is not a binary search tree but a plain binary tree. Any set of nodes can be a preorder notation. Suppose there is a binary tree a,b,c,d,e,f,g,h and your subtree is cdef. You can create another tree with subtree cde and another subtree fg. There is no way to know the difference.

    If it is a binary search tree however you needn't have the inorder.

    Incidentally here's an amusing algorithmic problem: given a preorder notation find the number of binary trees that satisfy it.

    0 讨论(0)
  • 2020-12-10 17:12

    As supplement to user1952500's answer: if it is a binary search tree, either only preorder or only postorder can make it unique, while only inorder can not. For example:

      5
     / \
    3   6
    

    inorder: 3-5-6 however, another binary search tree can have the same inorder:

    3
     \
      5
       \
        6
    

    Also, I believe preorder+inorder+string_comparison only works to check whether two trees are identical. It fails to check whether a tree is the subtree of another tree. To see an example, refer Determine if a binary tree is subtree of another binary tree using pre-order and in-order strings

    0 讨论(0)
  • 2020-12-10 17:17

    a preorder traversal with sentinel to represent null node is well enough. we can use this approach to serialize/deserialize binary tree. it means there is one-to-one mapping between a binary tree and its preorder with sentinel representation.

    0 讨论(0)
提交回复
热议问题