1ms O(1) extra space level order with the help of the previously set next pointer


  • 0
    I
     public class Solution {
        public void connect(TreeLinkNode root) {
            if(root != null){
                TreeLinkNode startingPoint = root.left;
                TreeLinkNode parent = root;
                TreeLinkNode node = startingPoint;
                while(node != null){
                    if(node == parent.left){
                        node.next = parent.right;
                        node = node.next;
                    }
                    else if(node == parent.right){
                        if(parent.next != null){
                            node.next = parent.next.left;
                            node = node.next;
                            parent = parent.next;
                        }
                        else {
                            node = startingPoint.left;
                            parent = startingPoint;
                            startingPoint = startingPoint.left;
                        }
                    }
                }
            }
        }
    }

Log in to reply
 

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