(Java)leetcode-230 Kth Smallest Element in a BST

Title Description

[Binary search tree in a small element of K]
Given a binary search tree, write a function kthSmallest to find where the k-th smallest element.

Note:
You can assume that k is always active, 1 ≤ k ≤ 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
Advanced:
If binary search trees are often modified (insertion / deletion) and you need to find the smallest value k frequently, how you will optimize kthSmallest function?

Thinking

Binary search trees (binary search tree, binary sort tree, the BST) in preorder is its val all nodes in ascending order. Thus, according to the order traversal, each element is determined whether he find a k-th element can be.

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int i = 0;
    private int val = 0;

    public int kthSmallest(TreeNode root, int k) {
        inorder(root, k);
        return val;
    }

    public void inorder(TreeNode root, int k) {
        if (root == null) {
            return;
        }
        inorder(root.left, k);
        if (k == ++i) {
            val = root.val;
            return; //只能省略第k小的结点的右子树的遍历(如果有右子树的话)
        }
        inorder(root.right, k);
    }
}
Published 143 original articles · won praise 45 · views 70000 +

Guess you like

Origin blog.csdn.net/z714405489/article/details/103167153