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;
    }
}

 

posted @ 2019-08-18 10:14  南山南北秋悲  阅读(108)  评论(0编辑  收藏  举报