To find largest element smaller than K in a BST

前端 未结 5 1069
梦如初夏
梦如初夏 2020-12-25 14:11

Given a binary search tree and an integer K, i would like to find the largest element less than K.

In the below tree,

for K = 13, result = 12
for K =         


        
5条回答
  •  执笔经年
    2020-12-25 14:57

    I think the idea here is to record the last node after which you move to the right subtree. Therefore, the code will be (has been updated)

    int findNum (Node *node, int K)
    {
        Node* last_right_move = NULL;
    
        while (node)
        {
            if (K<=node->data)
                node = node->left;
            else
            {
                last_right_move = node;
                node = node->right;
            }
        }
    
        if (last_right_move)
            return last_right_move->data;
        else
            return NOT_FOUND;  // defined previously. (-1 may conflict with negative number)
    }
    

提交回复
热议问题