My code beats 95.82% of java submissions.


  • 0
    T

    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)
                return;
            dfs(root.left, k);
            n++;
            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.