0

This question has already been asked here: http://stackoverflow.com/questions/14092710/equality-of-two-binary-search-trees-constructed-from-unordered-arrays.

However, the solution that I thought of is fairly simple but hasn't been mentioned there.

The problem statement is: Given two arrays which represent a sequence of keys. Imagine we make a Binary Search Tree (BST) from each array. We need to tell whether two BSTs will be identical or not without actually constructing the tree.

Something that I thought of is, just sort the two arrays. If they are identical, then their inorder traversal will also be identical and hence if the two arrays are identical, then they definitely will lead to the same BST. Am I wrong in assuming that if the inorder traversal of two binary search trees is same, then trees will be same too?

John Lui
  • 1,434
  • 3
  • 23
  • 37

2 Answers2

1

Only inorder traversal can not define a unique BST. You have to get another pre/post order traversal to reconstruct the very BST.

matrixit
  • 314
  • 3
  • 10
1

Unless I'm misunderstanding what you mean by "inorder traversal", this won't work. Not only are inorder traversals of BSTs not unique, in fact the inorder traversal of every BST on the same set of elements is the same. Here's a small example:

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

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

Both trees have the inorder traversal 1, 2, 3, 4, 5. So your approach will report "IDENTICAL" even though the trees are different.

Your approach is actually wrong in the other direction too. If the two BSTs have the same structure but different elements, then you should report "IDENTICAL", but of course their sorted lists ( = inorder traversals) are different -- so in this case you will report "DIFFERENT".

j_random_hacker
  • 50,331
  • 10
  • 105
  • 169