1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public Node connect(Node root) { if (root == null) { return null; } Node res = root; while (root != null) { Node nextLayerHead = new Node(0); Node nextLayerNode = nextLayerHead; while (root != null) { if (root.left != null) { nextLayerNode.next = root.left; nextLayerNode = nextLayerNode.next; } if (root.right != null) { nextLayerNode.next = root.right; nextLayerNode = nextLayerNode.next; } root = root.next; } root = nextLayerHead.next; } return res; } }
|