문제

Is there a way to find the number (count only) of nodes between 2 given nodes in a balanced binary search tree using their ranks in < O(log n) time?

We can assume that we already store each Node's rank (or height) dynamically as the Node class' member variable. So, we can access it directly.

도움이 되었습니까?

해결책

Yes, using lowest common ancestor queries it is possible to count the nodes in between in constant time. It requires a one time preprocessing of the tree in linear time.

If you know the rank of the lowest common ancestor of two nodes, then you can compute how many nodes are between a node and the ancestor by subtracting the rank of the ancestor from the rank of the child node.

nodes_between = a.rank + b.rank - 2*(lowest_common_ancestor(a, b).rank) + 1

The above will return the length of the path between nodes a and b including the two end point. The + 1 is for the lowest common ancestor itself. Finding the lowest_common_ancestor can be done in constant time and the calculation is constant time.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top