Skip to main content

116. Populating Next Right Pointers in Each Node

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

Python

class Solution:
def connect(self, root):
if root is None:
return root
self._connect(root.left, root.right)
return root

def _connect(self, node1, node2):
if node1 is None or node2 is None:
return None
node1.next = node2
self._connect(node1.left, node1.right)
self._connect(node2.left, node2.right)
self._connect(node1.right, node2.left)

Go

func connect(root *Node) *Node {
if root == nil {
return nil
}

connectTwo(root.Left, root.Right)
return root
}

func connectTwo(left *Node, right *Node) *Node {
if left == nil || right == nil {
return nil
}

left.Next = right
connectTwo(left.Left, left.Right)
connectTwo(right.Left, right.Right)
connectTwo(left.Right, right.Left)
return nil
}

Javascript

  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;