/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ publicclassSolution{ publicvoidconnect(TreeLinkNode root){ TreeLinkNode cur = root; // current node in the upper level TreeLinkNode head = null; // left most node in the lower level TreeLinkNode prev = null; // previous node in the same level while (cur != null) { while (cur != null) { if (cur.left != null) { if (prev != null) { prev.next = cur.left; } else { head = cur.left; } prev = cur.left; } if (cur.right != null) { if (prev != null) { prev.next = cur.right; } else { head = cur.right; } prev = cur.right; } cur = cur.next; } cur = head; prev = null; head = null; } } }