117. Populating Next Right Pointers in Each Node II

202407301905
tags: #linked-list

const levelOrderTraversal = (root, list, depth) => {
	if (root === null) {
		return;
	}
	if (list.length <= depth) {
		list.push([]);
	}
	list[depth].push(root);
	levelOrderTraversal(root.left, list, depth + 1);
	levelOrderTraversal(root.right, list, depth + 1);
}

var connect = function(root) {
	const levelList = [];
	levelOrderTraversal(root, levelList, 0);
	for (const list of levelList) {
		for (let i = 0; i < list.length - 1; i++) {
			list[i].next = list[i + 1];
		}
	}
	return root;
};

Reference

https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/