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

思路:中序遍历 递归 / 非递归

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