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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import static org.junit.Assert.assertSame;
public class PopulatingNextRightPointersInEachNodeII { public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode head = null; TreeLinkNode prev = null; TreeLinkNode curr = root; while (curr != null) { while (curr != null) { if (curr.left != null) { if (prev == null) { head = curr.left; } else { prev.next = curr.left; } prev = curr.left; } if (curr.right != null) { if (prev == null) { head = curr.right; } else { prev.next = curr.right; } prev = curr.right; } curr = curr.next; } curr = head; head = null; prev = null; } } @Test public void test() { TreeLinkNode root = new TreeLinkNode(1); root.left = new TreeLinkNode(2); root.right = new TreeLinkNode(3); root.left.left = new TreeLinkNode(4); root.left.right = new TreeLinkNode(5); root.right.right = new TreeLinkNode(7); connect(root); assertSame(root.left.right.next, root.right.right); } }
|