230. Kth Smallest Element in a BST

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了230. Kth Smallest Element in a BST相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 230. Kth Smallest Element in a BST

Leetcode 230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

230.Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

230.Kth Smallest Element in a BST