0

What is the best way to create a method that determines the height of a Binary Search Tree class? For instance: bst.height() would return 1 if it contains only 1 item; return 2 if it contains 3 items and is balanced, or return 3 otherwise; return 3 if it contains 4 items and is balanced, or return 4 otherwise. This may be a somewhat different implementation than usual.

user3020033
  • 15
  • 1
  • 10
  • 1
    You can think of height of a node being max(leftSubtree,rightSubtree)+1. Using this, you can work your way up to root level – anonymous Apr 30 '14 at 04:41
  • Possible duplicate of "The best way to calculate the height of a binary search tree": http://stackoverflow.com/q/575772/716443 – DavidO Apr 30 '14 at 04:45
  • @DavidO Yes, but I'm not referring to a self-balancing tree. – user3020033 Apr 30 '14 at 04:58
  • If the tree isn't self-balancing, and you input fully sorted data one element at a time, you will end up with a tree that has one long leg, and one missing leg; practically a flat linked list. That means your worst case for "walking the tree" will be O(n). It's probably best, in such a situation, to keep track upon insert, delete, and rebalance. That would give you an O(1) answer every time, at the small overhead of keeping track on the fly. – DavidO Apr 30 '14 at 05:09

1 Answers1

1

The fastest way would be to update the height while you insert and delete.

kec
  • 1,987
  • 8
  • 15