Why memory limit exceed without the two statements


  • 0
    L

    This is my original code :

    public TreeNode upsideDownBinaryTree(TreeNode root) {
        // recursive
        if(root == null) return root;
    
        if(root.left != null){
            TreeNode newRoot = upsideDownBinaryTree(root.left);
            root.left.left = root.right;
            root.left.right = root;
    
            return newRoot;
        }else { 
            return root;
        }
    }
    

    It seems to be an infinite loop.
    Then I looked at https://leetcode.com/discuss/30243/recursive-java-solution. I find

            root.left = null;
            root.right = null;
    

    should be added before return. May I know why? Thanks a lot!


  • 0
    L

    My fault. You need to "end" a tree. Otherwise when OJ check it, it will go back from root to its children and there is no end.


Log in to reply
 

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