In Order Successor in Binary Search Tree

前端 未结 17 1835
孤独总比滥情好
孤独总比滥情好 2020-11-27 04:11

Given a node in a BST, how does one find the next higher key?

17条回答
  •  粉色の甜心
    2020-11-27 04:49

    These answers all seem overly complicated to me. We really don't need parent pointers or any auxiliary data structures like a stack. All we need to do is traverse the tree from the root in-order, set a flag as soon as we find the target node, and the next node in the tree that we visit will be the in order successor node. Here is a quick and dirty routine I wrote up.

    Node* FindNextInorderSuccessor(Node* root, int target, bool& done)
    {
        if (!root)
            return NULL;
    
        // go left
        Node* result = FindNextInorderSuccessor(root->left, target, done);
        if (result)
            return result;
    
        // visit
        if (done)
        {
            // flag is set, this must be our in-order successor node
            return root;
        }
        else
        {
            if (root->value == target)
            {
                // found target node, set flag so that we stop at next node
                done = true;
            }
        }
    
        // go right
        return FindNextInorderSuccessor(root->right, target, done);
    }
    

提交回复
热议问题