The K-th smallest element in binary search tree

Keywords: Python

The K-th smallest element in binary search tree

LeetCode Chinese

LeetCode English

Given a binary search tree, write a function kthSmallest to find the k-th smallest element.

Explain:

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

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
 Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
 Output: 3

Advance:

How do you optimize the kthSmallest function if the binary search tree is frequently modified (insert / delete operations) and you need to find the k-th smallest value frequently?

Answer

The middle order traverses the binary search tree. In the process of traversing, each node will reduce K by 1. When k == 0, the k-th smallest element (pay attention to the boundary) is found.

C++ code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void recursion(TreeNode* root,int& res,int& k)
    {
        if(!root)
            return;
        
        recursion(root->left,res,k);
        
        k--;
        if(k == 0)
        {
            res = root->val;
            return;
        }
            
        recursion(root->right,res,k);
    }
    
    int kthSmallest(TreeNode* root, int k) {
        int res;
        recursion(root,res,k);
        
        return res;
    }
};

Python code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        self.k = k
        self.inorder(root)
        return self.res
        
    def inorder(self,root) -> bool:
        if root is None:
            return False
        
        if self.inorder(root.left):
            return True
            
        self.k -= 1
        if self.k == 0:
            self.res = root.val
            return True
            
        if self.inorder(root.right):
            return True
        
        return False
        
        

Posted by adcripps on Fri, 08 Nov 2019 14:18:36 -0800