方法:使用已建立的next 指针
思路:
一棵树中,存在两种类型的 next 指针。
第一种情况是连接同一个父节点的两个子节点。它们可以通过同一个节点直接访问到
node.left.next = node.right;
第二种情况在不同父亲的子节点之间建立连接,这种情况不能直接连接。
node.right.next = node.next.left;
var connect = function(root) {
if (root === null) {
return root;
}
// 从根节点开始
let leftmost = root;
while (leftmost.left !== null) {
// 遍历这一层节点组织成的链表,为下一层的节点更新 next 指针
let head = leftmost;
while (head !== null) {
// CONNECTION 1
head.left.next = head.right;
// CONNECTION 2
if (head.next != null) {
head.right.next = head.next.left;
}
// 指针向后移动
head = head.next;
}
// 去下一层的最左的节点
leftmost = leftmost.left;
}
return root;
};