您的位置:首页 > 编程语言 > Java开发

(java) Kth Smallest Element in a BST

2016-03-06 20:37 441 查看
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?

Hint:

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

思路1:中序遍历,然后输出第k的树就是结果

思路2:一个节点计算它的左子树节点数left

if left+1=k 则这个数就是要找的那个数

if left+1<k 则 k=k-left-1在右字数中找

if(left+1)>k 则在左子树中找

给出了思路1的代码,思路2的代码也不难写

代码如下(已通过leetcode)

public class Solution {

public int kthSmallest(TreeNode root, int k) {

List<Integer> list=new ArrayList<Integer>();

InOrderTravel(list,root);

return list.get(k-1);

}

private void InOrderTravel(List<Integer> list, TreeNode root) {

// TODO Auto-generated method stub

if(root==null) return;

if(root.left!=null) InOrderTravel(list, root.left);

list.add(root.val);

if(root.right!=null) InOrderTravel(list, root.right);

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: