My code beats 95.82% of java submissions.

  • 0

    the extra space is O(logn) of system stack, the time is O(logn + k).

    public class Solution {
        int n = 0;
        int result = -1;
        public int kthSmallest(TreeNode root, int k) {
            dfs(root, k);
            return result;
        void dfs(TreeNode root, int k){
            if (root == null || n >= k)
            dfs(root.left, k);
            if (n == k)
                result = root.val;
            dfs(root.right, k);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.