标签:problems com code stack blog public int null while
https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/solutions
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
TreeNode node = stack.pop();
if(--k == 0) return node.val;
cur = node.right;
}
return root.val;
}
递归:
public class Solution {
int count = 0;
public int kthSmallest(TreeNode root, int k) {
List<Integer> res = new ArrayList<Integer>();
res.add(null);
helper(root, k, res);
return res.get(0);
}
public void helper(TreeNode root, int k, List<Integer> res) {
if (root == null) return;
helper(root.left, k, res);
count++;
if (count == k) res.set(0, root.val);
helper(root.right, k, res);
}
}
230. Kth Smallest Element in a BST
标签:problems com code stack blog public int null while
原文地址:http://www.cnblogs.com/apanda009/p/7099223.html