1

Here are the combinations of different BSTs with same element, the arrangement looks different depending on the sequence of addition of nodes to the tree structure:

  1             1           1                    1         1
   \             \           \                    \         \
    2             2           3                    4         4 
     \             \         / \                  /         /
      3             4       2   4                3         2
       \           /                            /           \
        4         3                            2             3




  2           2          3        3             4         4         4      
 / \         / \        / \      / \           /         /         /      
1   3       1   4      2   4    1   4         3         2         3      
     \         /      /          \           /         / \       /         
      4       3      1            2         2         1   3     1          
                                           /                     \          
                                          1                       2        



  4         4
 /         /
1         1 
 \         \
  2         3 
   \        /
    3      2

Their in-order traversal will be same, so how do we distinguish them? Especially when there are more than one sequence of adding the nodes and they all generate the same structure, example 2,1,4,5,2,4,1,3,2,4,3,1.

Gaurav
  • 1,570
  • 5
  • 17
  • 1
    Your third example is not a valid BST. Everything to the right of `3` must be greater than or equal to `3`. But in this example, `2` is a child of `4`. The inorder traversal will be 1-3-2-4. – Jim Mischel Jun 08 '19 at 22:30
  • 1
    You can tell the difference between two trees by doing a [breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search).. – Jim Mischel Jun 08 '19 at 22:32
  • @JimMischel Thanks a lot!! going to try it now. – Gaurav Jun 08 '19 at 22:34

1 Answers1

1

You mentioned that all your examples have the same in-order traversal (1234), meaning inorder is not enough information to derive the tree structure. However, both post-order and pre-order sequences are sufficient for deriving the tree structure of a binary search tree.

For example, given the pre-order 2-1-3-4, the only binary search tree that satisfies this pre-order is your row 2 col 1 example. Compare that to pre-order 2-1-4-3 which would be your row 2 col 2 example.

For all of your examples, here are their pre-order notations

[1234] [1243] [1324] [1432] [1423]

[2134] [2143] [3214] [3124] [4321] [4213] [4312]

[4123] [4132]

As you can see, they are all distinct. You can repeat the same process for their post-order traversal, and you should get all distinct results.

Community
  • 1
  • 1
Peter Cheng
  • 758
  • 7
  • 9