LeetCode 230 Kth Smallest Element in a BST

来源:互联网 发布:淘宝浏览单佣金3 3 3 编辑:程序博客网 时间:2024/05/22 21:21

题目描述

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

Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

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?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node’s structure?
  3. The optimal runtime complexity is O(height of BST).

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


分析

因为是BST,那么中序遍历即得到从小到大的序列。中序遍历,到第k次即可。


代码

    public int kthSmallest(TreeNode root, int k) {        if (root == null) {            return -1;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode p = root;        while (p != null || !stack.isEmpty()) {            while (p != null) {                stack.push(p);                p = p.left;            }            if (!stack.isEmpty()) {                p = stack.pop();                if (--k == 0) {                    return p.val;                }                p = p.right;            }        }        return 0;    }
2 0