To find largest element smaller than K in a BST

前端 未结 5 1049
梦如初夏
梦如初夏 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:49

    That's O(log n), which is the minimum. However, you can improve the efficiency (which seems to be the main thing these interviewers care about) and eliminate the possibility of stack overflow (tada!) by eliminating tail recursion, turning this into a loop. Also, your code doesn't work if the tree contains negative numbers ... if you mean non-negative integers, you should say so, but if the interviewer just said "integers" then you need slightly different code and a different API. (You could keep the same function signature but return K instead of -1 upon failure.)

    BTW, since this is an interview question, implementing it by calling a library function would tell most interviewers that you are a smartass or are missing the point or don't know how to solve it. Don't mess around with that sort of thing, just get to working on what you know the interviewer wants.

    Here is an implementation:

    // Return the greatest int < K in tree, or K if none.
    int findNum (Node* tree, int K)
    {
        int val = K;
    
        while( tree )
            if( tree->data >= K )
                tree = tree->left;
            else{
                val = tree->data; 
                tree = tree->right;
            }
    
        return val;
    }
    

提交回复
热议问题