您的位置:首页 > 其它

230. Kth Smallest Element in a BST

2017-04-29 21:27 274 查看
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?

Credits:

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

Subscribe to see which companies asked this question.

Java Code:

/**
* 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) {
int[] cnt = {0};
int[] result = {root.val};
kthSmallest(root, k, cnt, result);

return result[0];
}

public void kthSmallest(TreeNode root, int k, int[] cnt, int[] result) {
if (root == null) {
return;
}
if (cnt[0] != k) {
kthSmallest(root.left, k, cnt, result);
cnt[0]++;
}
if (cnt[0] == k) {
result[0] = root.val;
return;
}
kthSmallest(root.right, k, cnt, result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Kth Smallest Element