To find largest element smaller than K in a BST

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

    What the first answer said, and here is the logic behind why it cannot get better than O(log n). You are looking for the largest number less than K. This is quite close to calling BST-search/get .

    Although your original algorithm looks quite good, I think this would be faster:

        int findNum (node root, int K) {
            if(root == null) return -1;
    
            if(K > root.val) { 
               if(root.right != null) return findNum(root.right, K);               
               else return root.val; 
            }
    
            return findNum(root.left, K); //look in left subtree
    
        }
    

提交回复
热议问题