Accepted java solution


  • 0
    J
    public void connect(TreeLinkNode root) 
        {
            if (root == null) return;
            FirstPart(root);
            SecondPart(root);
           // ThirdPart(root);
        }
        
        private void FirstPart(TreeLinkNode root)
        {
            if (root == null) return;
           // root.left.next = root.right;
            
            leftchild = root.left;
            rightchild = root.right;
            while(leftchild != null && rightchild != null)
            {
                leftchild.next = rightchild;
                leftchild = leftchild.right;
                rightchild = rightchild.left;
            }
            FirstPart(root.left);
            FirstPart(root.right);
        }
        
        private TreeLinkNode leftchild;
        private TreeLinkNode rightchild;
        
        private void SecondPart(TreeLinkNode root)
        {
            if (root == null) return;
            root.next = null;
            SecondPart(root.right);
        }
    

Log in to reply
 

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