public void connect(TreeLinkNode root) { if (root == null || (root.left == null && root.right == null)) return; TreeLinkNode current = null; if (root.left != null && root.right != null) { root.left.next = root.right; current = root.right; } else { current = root.left != null ? root.left : root.right; } TreeLinkNode rootNext = root.next; while (rootNext != null) { if (rootNext.left != null || rootNext.right != null) { current.next = rootNext.left != null ? rootNext.left : rootNext.right; break; } rootNext = rootNext.next; } connect(root.right); //先连右边!!! connect(root.left); }
public void connect(TreeLinkNode root) { if (root == null || root.left == null) return; //完美树,如果没有左子,则一定没有右子 root.left.next = root.right; if (root.next != null) root.right.next = root.next.left; connect(root.left); connect(root.right); }
public void OJ117_PopulatingNextRightPointersInEachNodeIITest1() { 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); new OJ117_PopulatingNextRightPointersInEachNodeII().connect(root); Assert.AreEqual(3, root.left.next.val); Assert.AreEqual(5, root.left.left.next.val); Assert.AreEqual(7, root.left.left.next.next.val); }