Note 1: that using recursion has memory overhead and does not qualify for constant space. Note 2: The tree need not be a perfect binary tree.
Method:
Use the next pointer to traverse current level, keep track of a previous node in next level and also keep track of the start of next level. (If prev is null, then set the start)
Solution:
Time: O(n) Space: O(1)
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class Solution { public void connect(TreeLinkNode root) { TreeLinkNode levelStart = root; while (levelStart != null) { TreeLinkNode curr = levelStart; TreeLinkNode prev = null; // set next level start to null, otherwise never end levelStart = null; while (curr != null) { for (TreeLinkNode child : Arrays.asList(curr.left, curr.right)) { if (child != null) { // this child will be the first node of next level if (prev == null) { levelStart = child; } else { prev.next = child; } prev = child; } } curr = curr.next; } } } }