Help ! why is this memory limit exceed

  • 0
            if (root == null) return null ;
            Stack<TreeNode> s = new Stack<TreeNode>() ;
            while( s.peek().left != null || s.peek().right != null ){
                TreeNode temp = s.peek() ;
                if (temp.right != null) s.push(temp.right);
                if (temp.left != null) s.push(temp.left);
            TreeNode head = s.pop();
            TreeNode prev = head ;
            while (!s.empty()){
                prev.left = s.pop();
                if(!s.empty()) prev.right = s.pop();
                prev = prev.right ;
            return head ;

  • 0

    I think you there is a cycle in the 'tree' you created. So when the solver try to check some test case, it will stuck into some infinite loop.
    What I mean is that, your algorithm will use only finite time. But the checking part will use infinite time.

Log in to reply

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