给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
思路吧每一层拿出来循环遍历,在层次遍历的过程中将我们将二叉树每一层的节点拿出来遍历并连接。
每次循环当前节点,吧当前节点的子节点放入 数组,
如果到达每层最后一个节点,则不需要指向下一节点
var connect = function(root) {
// 判断节点
if(root === null){
return root
}
// 记录初始长度,不会因为操作数组,改变数组长度
let Q = [root]
while(Q.length > 0){
const size = Q.length
for(let a = 0;a
const node = Q.shift()
// 判断当前节点 是否有右节点
if(a < Q.length -1){
node.next = Q[0]
}
if(node.left != null){
Q.push(node.left)
}
if(node.right != null){
Q.push(node.right)
}
}
}
return root
};



