LeetCode 230 Kth Smallest Element in a BST (中序遍历)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/89636107

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

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total 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

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

题目链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/

题目分析:中序遍历即可,至于follow up,对每个点记录其子树的size即可,插入删除操作只需修改到根路径上点的size即可

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int cnt = 0, ans = 0;
        Stack<TreeNode> stk = new Stack<>();
        while (root != null || !stk.empty()) {
            while (root != null) {
                stk.add(root);
                root = root.left;
            }
            if (!stk.empty()) {
                root = stk.pop();
                cnt++;
                if (cnt == k) {
                    ans = root.val;
                    break;
                }
                root = root.right;
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Tc_To_Top/article/details/89636107