题目内容
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?
题目分析
在二叉查找树中,找出第k小的数,直接中序遍历就可以了。迭代比递归快一些。
/**
* 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> stack =new Stack<TreeNode>();
int n=0;
int ans=0;
while(true){
while(root!=null){
stack.push(root);
root=root.left;
}
if(n<k){
n++;
TreeNode node=stack.pop();
root=node.right;
ans=node.val;
}
else{
return ans;
}
}
//return 0;
}
}