230. Kth Smallest Element in a BST

来源:互联网 发布:周杰伦 忍者 知乎 编辑:程序博客网 时间:2024/05/22 17:42

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.

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?

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int kthSmallest(TreeNode root, int k) {        Stack<TreeNode> data = new Stack<TreeNode>();while (root != null || !data.isEmpty()) {while (root != null) {data.push(root);root = root.left;}root = data.pop();k--;if (k == 0)return root.val;root = root.right;}return -1;    }}


0 0