Java clean solution


  • 0
    S

    public void connect(TreeLinkNode root) {
    if (root == null || root.left == null) return;

        //we move to second row
        TreeLinkNode currentLeftMost = root.left;
        
        //keep two layers reference
        TreeLinkNode parentNode = root;
        TreeLinkNode current = currentLeftMost;
        while(currentLeftMost != null) {
            //for one layer
            while(parentNode != null) {
                if (parentNode.left == current) {
                    current.next = parentNode.right;
                }
                else if (parentNode.right == current){
                    parentNode = parentNode.next;
                    if (parentNode == null) {
                        //finished one row
                        break;
                    }
                    current.next = parentNode.left;
                }
                current = current.next;
            }
            
            parentNode = currentLeftMost;
            currentLeftMost = parentNode.left;
            current = currentLeftMost;
        }
    }

Log in to reply
 

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