user2113735
user2113735

Reputation: 27

Height of binary search tree in constant time

I need to fine the height of a binary search tree with a time of O(1) the only way i could think to do this is to put a check in the add and remove methods incrementing a global counter is there any other way?

Upvotes: 1

Views: 2341

Answers (2)

Adrian Shum
Adrian Shum

Reputation: 40076

Storing an attribute for the height and update it when you are doing add/remove should be the most reasonable solution.

If the tree is guaranteed to be balanced (e.g. AVL), you can calculate the height by number of element in the tree (you have to keep the number of elements though :P )

Upvotes: 2

Avinash Singh
Avinash Singh

Reputation: 3797

O(1) time suggests that you should already have the height when it is requested.

The best way is it to keep/update the correct value whenever a new node is added/deleted . You are doing it in a right way , however it increases the complexity on addition and deletion.

You can do it number of ways , like keep the depth value along with the node in tree etc.

class Node{
int depth;
Object value;
}

Node lowestNode;

I can think of storing the max depth node reference in an object and keep that as depth . So whenever you add a new element , you can check the depth of element based on its parent and replace the max depth node if the new element has more depth .

If you are deleting the max depth node then replace it with the parent otherwise correct the depth of all elments recursively along the tree.

The height of tree is , lowestNode.depth

Upvotes: 3

Related Questions