230. Kth Smallest Element in a BST
不要被题目迷惑,肯定是要O(N)的时间,在不改变数据结构的情况下。 就是in-order traverse,因为是BST,所以遍历顺序是从小到大,遍历的第K个元素就是第K小的。 可以Iteratively,也开始recursively. public class Solution { /* recursion version int count = 0; int res = 0; public int kthSmallest(TreeNode root, int k) { helper(root,k); return res; } public void helper(TreeNode root, int k) { if(root == null || count == k) return; helper(root.left,k); count++; if(count == k) { res = root.val; return; } helper(root.right,k); } */ public int kthSmallest(TreeNode root, int k) { int res = 0; int count = 0; Stack<TreeNode> stk = new Stack<TreeNode>(); TreeNode temp = root; while