K-th smallest element in binary search tree javascript

Given a binary search tree, write a function kthSmallest to find the kth smallest element.

Explanation:
You can assume that k is always valid, and 1 ≤ k ≤ the number of elements in the binary search tree.

Example 1:

Input: the root = [3,1,4, null, 2], K = 1
. 3
/
1. 4

2
Output: 1
Example 2:

Input: the root = [5,3,6,2,4, null, null,. 1], K = 3
. 5
/
3. 6
/
2. 4
/
. 1
Output: 3

var kthSmallest = function(root, k) {
        var result=[]
        function serchkey(node) {
            if(node){
            serchkey(node.left)
            result.push(node.val)
            serchkey(node.right)
        } 
    }
     serchkey(root)
      return result[k-1]
}

Ideas:
1. In-order traversal and push into the array
2. Output the k-1th

var kthSmallest = function(root, k) {
       function count(node){
           if(!node){
               return 0
           }else{
               return 1+count(node.left)+count(node.right)
           }
       }
       var leftnum=count(root.left)
       if(leftnum==k-1){
           return root.val
       }else if(leftnum<k-1){
           return kthSmallest(root.right,k-leftnum-1)
       }else if(leftnum>k-1){
           return kthSmallest(root.left,k)
       }
}

Guess you like

Origin blog.csdn.net/qq_41988554/article/details/104979501