Another accepted Java solution


  • 1

    Basically, we use the next pointer to help level traversal. No recursion is needed, O(1) constant space, O(n) running time.

    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root == null) return;
            
            while (root.left != null) {
                TreeLinkNode curr = root;
                
                while (curr != null) {
                    curr.left.next = curr.right;
                    curr.right.next = curr.next != null ? curr.next.left : null;
                    curr = curr.next;
                }
                
                root = root.left;
            }
        }
    }

Log in to reply
 

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