算法: 搜索二叉树搜索第k个最小数230. Kth Smallest Element in a BST

Posted 架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 搜索二叉树搜索第k个最小数230. Kth Smallest Element in a BST相关的知识,希望对你有一定的参考价值。

230. Kth Smallest Element in a BST

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Example 1:

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

Example 2:

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

Constraints:

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 104
  • 0 <= Node.val <= 104

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

1. DFS 中序递归:

时间复杂度:O(N)

 // better keep these two variables in a wrapper class
  private static int number = 0;
  private static int count = 0;

  public int kthSmallest(TreeNode root, int k) {
      count = k;
      helper(root);
      return number;
  }
  
  public void helper(TreeNode n) {
      if (n.left != null) helper(n.left);
      count--;
      if (count == 0) {
          number = n.val;
          return;
      }
      if (n.right != null) helper(n.right);
  }

2. DFS 中序迭代:

时间复杂度:O(N) 最好

public int kthSmallest(TreeNode root, int k) {
      Stack<TreeNode> st = new Stack<>();
      
      while (root != null) {
          st.push(root);
          root = root.left;
      }
          
      while (k != 0) {
          TreeNode n = st.pop();
          k--;
          if (k == 0) return n.val;
          TreeNode right = n.right;
          while (right != null) {
              st.push(right);
              right = right.left;
          }
      }
      
      return -1; // never hit if k is valid
}

参考

https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63660/3-ways-implemented-in-JAVA-(Python)%3A-Binary-Search-in-order-iterative-and-recursive

以上是关于算法: 搜索二叉树搜索第k个最小数230. Kth Smallest Element in a BST的主要内容,如果未能解决你的问题,请参考以下文章

题目地址(230. 二叉搜索树中第K小的元素)

leetcode230二叉树中第K小的元素

230. 二叉搜索树中第K小的元素二叉搜索数

230. 二叉搜索树中第K小的元素

Leetcode 230.二叉搜索树第k小的数

LeetCode——230. 二叉搜索树中第K小的元素(Java)