230. 二叉搜索树中第K小的元素

152 阅读1分钟

题目

image.png

思路

  • 由于是求第K小,直接按照左 中 右的顺序遍历。

代码

class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        int count = 0;
        while (!stack.isEmpty() || node != null) {
            if (node != null) {
                stack.push(node);
                node = node.left;
            } else {
                TreeNode father = stack.pop();
                count++;
                if (count == k) {
                    return father.val;
                }
                node = father.right;
            }
        }
        return 0;
    }
}