1. 程式人生 > >230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

pro new lee public http ack urn nod light

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