题目:
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.
4
/ \
2 6
/ \ / \
1 3 5 7
分析:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
//给定一颗从左到右的按顺序的二叉树,找出其中第k小的数
//思路:因为从左到右依次增大的树,那么中序遍历即可满足条件
List<Integer> list=new ArrayList<>();
backtrace(root,list,k);
return list.get(k-1);
}
//中序递归
public void backtrace(TreeNode root,List<Integer> list,int k){
//出口
if(list.size()>=k){
return ;
}
if(root.left!=null){
backtrace(root.left,list,k);
}
list.add(root.val);
if(root.right!=null){
backtrace(root.right,list,k);
}
}
}