Memory Limit Exceeded - Java. Not declaring any new Nodes.


  • 0
    V

    Why does this give me Memory Limit Exceeded? As far as I know I am not declaring any extra memory. All I am doing is declaring references (pointers).

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void flatten(TreeNode root) {
            if(root==null)
                return;
            if(root.left==null){
                //System.out.println("Root.left is null for "+root.val);
                return;
            }
            else if(root.left.left==null){
                //System.out.println("Attaching "+root.right.val+" to "+root.left.val);
                attachToEndOfRightBranchOf(root.left, root.right);
                //System.out.println("Attaching "+root.left.val+" to "+root.val);
                makeRightChildOf(root, root.left);
            }
            else flatten(root.left);
        }
        void attachToEndOfRightBranchOf(TreeNode root, TreeNode toBeAttached){
            TreeNode current = root;
            while(current.right!=null){
                current = current.right;
            }
            current.right = toBeAttached;
        }
        
        void makeRightChildOf(TreeNode root, TreeNode child){
            if(root.right==null){
                root.right=child;
                return;
            }
            TreeNode current = child;
            //TreeNode oldRightChild = root.right;
            while(current.right!=null)
                current = current.right;
            current.right = root.right;
            root.right = child;
        }
    }

Log in to reply
 

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