# LeetCode: Populating Next Right Pointers in Each Node Solution

BFS with level

## Approach: BFS

Grab all nodes with the same level and work on them

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var connect = function (root) {2  if (!root) return null3
4  let queue = []5  let accLevel = 06
7  const addLevel = (node, level = 0) => {8    if (!node) return9    node.level = level10    addLevel(node.left, level + 1)11    addLevel(node.right, level + 1)12  }13
16  queue.push(root)17
18  while (queue.length > 0) {19    const nodes = []20
21    while (queue.length > 0 && queue[0].level === accLevel) {22      nodes.push(queue.shift())23    }24
25    for (let i = 0; i < nodes.length; i++) {26      nodes[i].next = nodes[i + 1] || null27      if (nodes[i].left) {28        queue.push(nodes[i].left, nodes[i].right)29      }30    }31
32    accLevel++33  }34
35  return root36}```

## Approach: Recursive

The most important part is to connect

next
of 2 subtrees

## Implementation

```1var connect = function (root) {2  if (!root) return null3  if (!root.left) return root4
5  root.left.next = root.right6  if (root.next) {7    root.right.next = root.next.left8  }9  connect(root.left)10  connect(root.right)11
12  return root13}```

leetcode

tree

binary tree

bfs

recursion

## Next Post

LeetCode: 01 Matrix

Sep 24, 2021

## Previous Post

CSSBattle 15.81: Odoo

Sep 22, 2021

Flexbox, pseudo-classes, pseudo-elements

Search Posts