Leetcode230. 二叉搜尋樹中第K小的元素

Loser_you發表於2020-12-23

Leetcode230. 二叉搜尋樹中第K小的元素

class Solution {
    public int kthSmallest(TreeNode root, int k) {
        List<Integer> result = new ArrayList<>();
        dfs(result, root);
        if (result.isEmpty()) {
            return -1;
        }
        Collections.sort(result);
        return result.get(k - 1);
    }

    private void dfs(List<Integer> result, TreeNode root) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        dfs(result, root.left);
        dfs(result, root.right);
    }
}
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        LinkedList<TreeNode> stack = new LinkedList<>();

        while (true) {
            while (root != null) {
                stack.add(root);
                root = root.left;
            }
            root = stack.removeLast();
            if (--k == 0) {
                return root.val;
            }
            root = root.right;
        }
    }
}

相關文章