(medium)LeetCode 230.Kth Smallest Element in a BST
Posted on 2015-08-05 18:33 骄阳照林 阅读(148) 评论(0) 编辑 收藏 举报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?
代码1:
/** * 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) { int count =countNodes(root.left); if(k<=count){ return kthSmallest(root.left,k); }else if(k>count+1){ return kthSmallest(root.right,k-1-count); } return root.val; } public int countNodes(TreeNode n){ if(n==null) return 0; return 1+countNodes(n.left)+countNodes(n.right); } }
运行结果:
代码2:中序遍历递归
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private static int number=0; private static int count=0; public int kthSmallest(TreeNode root, int k) { count=k; helper(root); return number; } public void helper(TreeNode n){ if(n.left!=null) helper(n.left); count--; if(count==0){ number=n.val; return; } if(n.right!=null) helper(n.right); } }
运行结果:
代码3:中序遍历迭代
/** * 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>st=new Stack<>(); while(root!=null){ st.push(root); root=root.left; } while(k!=0){ TreeNode n=st.pop(); k--; if(k==0) return n.val; TreeNode right=n.right; while(right!=null){ st.push(right); right=right.left; } } return -1; } }
运行结果:
代码4:使用队列,中序遍历,存储起来,然后出队n个元素即可。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private Queue<TreeNode> queue=new LinkedList<TreeNode>(); public int kthSmallest(TreeNode root, int k) { inOrder(root); TreeNode ret=null; while(k>0){ ret=queue.poll(); k--; } return ret.val; } public void inOrder(TreeNode root){ if(root==null) return; if(root.left!=null) inOrder(root.left); queue.offer(root); if(root.right!=null) inOrder(root.right); } }
运行结果: