I tried to write recursively, but its having TLE..


  • 0
    R
    public void connect(TreeLinkNode root) {
            if(root == null) return;
            if(root.next != null) connect(root.next);
            if(root.left != null){
                if(root.right != null){
                    root.left.next = root.right;
                    root.right.next = getNext(root);
                }
                else
                    root.left.next = getNext(root);
                connect(root.left);
            }
            else if(root.right != null) {
                root.right.next = getNext(root);
                connect(root.right);
            }
            else connect(getNext(root));
        }
        
        public TreeLinkNode getNext(TreeLinkNode root){
            TreeLinkNode temp = root.next;
            while(temp != null){
                 if(temp.left != null) return temp.left;
                 else if(temp.right != null) return temp.right;
                 temp = temp.next;
            }
            return null;
        }

  • 0
    L

    You and me are just write exactly same code:


  • 0
    L

    all you need to do is connection right, then connection left. no need to connect(getNext(root)). {this costs time.}


Log in to reply
 

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