Height of binary search tree in constant time

不打扰是莪最后的温柔 提交于 2019-12-04 05:28:34

问题


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?


回答1:


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




回答2:


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 )



来源:https://stackoverflow.com/questions/15193306/height-of-binary-search-tree-in-constant-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!