My 12-line neat DFS java solution

  • 0
        public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> stack = new Stack<TreeNode>();
            while(!stack.isEmpty()) {
                while(stack.peek() != null) stack.push(stack.peek().left);
                if(k-- == 1) return stack.pop().val;
                else stack.push(stack.pop().right);
            return -1;

Log in to reply

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