Why always memory limit exceeded? Please help me


  • 0
    T

    I really can't figure out why it's always memory limit exceed. The only memory space I use us a pointer called node. Anyone could help me?

    /**

    • Definition for binary tree with next pointer.

    • public class TreeLinkNode {

    • int val;
      
    • TreeLinkNode left, right, next;
      
    • TreeLinkNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      TreeLinkNode node;
      public void connect(TreeLinkNode root) {
      if(root == null) return ;
      if(root.left == null && root.right == null) return;
      helper(root);
      }

      private void helper(TreeLinkNode root){
      if(root == null) return;
      if(root.left == null && root.right == null) return;
      if(root.left != null && root.right != null){
      root.left.next = root.right;
      }
      node = root;

      if(root.next != null){
           if(root.next.left == null && root.next.right == null){
               while(root.next != null && ((root.next.left == null & root.next.right == null))){
                   root = root.next;
               }
           }
           if(root != null){
               if(root.left != null){
       			if(node.right != null) node.right.next = root;
       			else node.left.next = root;
       		}
       		else if(root.right != null){
       		if(node.right != null) node.right.next = root;
       			else node.left.next = root;
       		}
           }
      }
      helper(node.left);
      helper(node.right);
      

      }

    }


  • 0
    C

    It's recursive nature pushes a new stack frame every time you call it on the left and on the right nodes and that takes up memory. Maybe try writing this iteratively?


Log in to reply
 

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