Next largest element in a binary search tree [closed]

时光怂恿深爱的人放手 提交于 2020-01-30 04:04:15

问题


I'm looking for a simple algorithm to find the next largest element (key) in a binary search tree, can anyone help?


回答1:


Assuming that by "next largest," you mean, the next largest node from wherever the current node is...

From the current node, go right once. You've gone to a higher valued node. Then, go left as many times as possible. You've ended at the lowest valued node which is still higher than where you started.


(source: ray at cs.lmu.edu)

Example. Start at 60, go right once, go left as many times as you can. You end up at 62.

Try the same thing for 41. You will end up at 42.

EDIT:

This should help with your second case. Pseudocode:

If (current.hasNoRightChild)
    testParent = current
    nextLargest = maxValueInTree
    While (testParent.hasParent)
        testParent = current.Parent
        If (testParent > current  && testParent < nextLargest)
            nextLargest = testParent
            While (testParent.hasLeftChild)
                testLeftChild = testParent.testLeftChild
                If (testLeftChild > current && testLeftChild < nextLargest)
                    nextLargest = testLeftChild
                End if
            End while
        End if
    End while
End if

Can't guarantee no bugs in that, but the general idea is you check each parent, slowly working your way to the top of the tree. At each node, you stop and see if it is a candidate to be the "next largest" (i.e. it is greater than the node you started from and less than the current guess of next largest). At each of these stops, if the node is greater than where you started, you must explore all the way down the subtree of that node on the left branch only, checking each value along the way. I think that should do it, but you should probably test it heavily with random values to make sure there aren't any other cases we've overlooked.




回答2:


Case 1: right (x) is non empty successor (x ) = the minimum in right (x) Case 2: right (x) is empty go up the tree until the current node is a left child: successor (x ) is the parent of the current node if you cannot go further (and you reached the root): x is the largest element



来源:https://stackoverflow.com/questions/13757413/next-largest-element-in-a-binary-search-tree

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