Link Each Node to Its Right Neighbour
Implement linkNeighbors
You are given the root of a binary tree in which every node has, besides its value and its left and right children, an extra pointer called next (initially null). Fill in every next pointer so that it points to the node immediately to the right on the same level; the rightmost node of each level keeps next = null. Return the root.
A queue that processes the tree one level at a time makes this easy. The classic refinement uses no queue at all: the next links of one level are used to walk it while the links of the level below are being created.
Example 1:
Input: root = [8,3,10,1,6,null,14,null,2]
Output: [-1,10,-1,6,14,-1,-1]
Example 2:
Input: root = [5,2]
Output: [-1,-1]
Example 3:
Input: root = []
Output: []
+ 11 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes ≤ 100; 0 ≤ node.val ≤ 1000 - ●
The tree is given as its root node (null for an empty tree). Besides val, left and right, every node has a next pointer that starts as null - ●
Set each node's next pointer to the node immediately to its right ON THE SAME LEVEL, or leave it null when the node is the rightmost of its level. Return the root - ●
The result is checked level by level: for every node in level order (left to right within a level) the value of its next node is reported, or -1 if next is null
root =