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).
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
ArrayList<Integer> al = new ArrayList<Integer>();
public int kthSmallest(TreeNode root, int k) {
ListAll(root);
return al.get(k-1);
}
public void ListAll(TreeNode root){
if(root!=null){
ListAll(root.left);
al.add(root.val);
ListAll(root.right);
}
}
}
总结,先插入把二叉排序树,中序遍历一遍,再插入链表中,全局的链表虽然这么用不是太好。。。