117. Populating Next Right Pointers in Each Node II
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii
Python
from collections import defaultdict
class Solution:
def __init__(self):
self.map = defaultdict(list)
def connect(self, root: 'Node') -> 'Node':
if root is None:
return root
self._travel(root.left, 1)
self._travel(root.right, 1)
for level in self.map:
reduce(self._link_nodes, self.map[level])
return root
def _link_nodes(self, node1, node2):
node1.next = node2
return node2
def _travel(self, node, level):
if not node:
return
self.map[level].append(node)
self._travel(node.left, level+1)
self._travel(node.right, level+1)
Javascript
var connect = function(root) {
const queue = [];
if (root) queue.push(root);
while (queue.length) {
const total = queue.length;
for (let i = 0; i < total; i++) {
const node = queue.shift();
if (i < total - 1) node.next = queue[0];
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return root;
};