Skip to content

填充每个节点的下一个右侧节点指针

LeetCode-116

js
var connect = function(root) {
  if(root === null) return null
  let q = [root]
  while(q.length) {
    let len = q.length
    for(let i = 0; i < len; i++) {
      let node = q.shift()
      // 这里添加判断的原因:每层最后一个节点不指向新入栈的节点(例如:3 --> 4)
      if(i < len - 1) node.next = q[0]
      if(node.left) q.push(node.left)
      if(node.right) q.push(node.right)
    }
  }
  return root
}