230. Kth Smallest Element in a BST java solutions

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:

  1. Try to utilize the property of a BST.Show More Hint 

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

 

Subscribe to see which companies asked this question

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     ArrayList<Integer> ans = new ArrayList<Integer>();
12     public int kthSmallest(TreeNode root, int k) {
13         InorderTree(root);
14         return ans.get(k-1);
15     }
16     
17     public void InorderTree(TreeNode node){
18         if(node != null){
19             InorderTree(node.left);
20             ans.add(node.val);
21             InorderTree(node.right);
22         }
23     }
24 }

非递归算法使用栈:

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int kthSmallest(TreeNode root, int k) {
12         Stack<TreeNode> s = new Stack<TreeNode>();
13         s.push(root);
14         TreeNode node = root;
15         while(!s.isEmpty()){
16             node = s.peek();
17             if(node.left != null){
18                 s.push(node.left);
19                 node.left = null;
20             }else{
21                 s.pop();
22                 k--;
23                 if(k == 0) return node.val;
24                 if(node.right != null) s.push(node.right);
25             }
26         }
27         return node.val;
28     }
29 }

 

posted @ 2016-06-23 10:09  Miller1991  阅读(175)  评论(0编辑  收藏  举报