Height of binary search tree in constant time

前端 未结 2 2051
轮回少年
轮回少年 2021-01-23 08:13

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

2条回答
  •  余生分开走
    2021-01-23 08:30

    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

提交回复
热议问题