leetcode 230. Kth Smallest Element in a BST

中序遍历,计数器数到k时,输出当前节点值

class Solution {
    private int count;
    public int kthSmallest(TreeNode root, int k) {
        count = 0;
        Stack<TreeNode> stack = new Stack<>();
        
        while(root != null){
            stack.push(root);
            root = root.left;
        }
        
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();
            count++;
            if(count == k)
                return cur.val;
            cur = cur.right;
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
        }
        
        return 0;
    }
}
原文地址:https://www.cnblogs.com/hwd9654/p/11371552.html