Populating Next Right Pointers in Each Node II
Every node of a binary tree has one more pointer, next, which starts as none. Point each node's next at the node to its right on the same level; the rightmost node of a level keeps none. The tree need not be full, so a level may have gaps. Return the root. Our example: the tree [6, 2, 9, 1, 4, none, 8] in level order — after the run the levels read 6 → none; 2 → 9 → none; 1 → 4 → 8 → none.
- input
root: a binary tree, written level by level as on LeetCode (nullwhere a child is missing); each node also has a pointernext,nullfor now.- returns
root, with each node’snextset to the node to its right on the same level, andnullfor the last node of a level. The tests print it as LeetCode does: each level bynext, then#.- constraints
- root is a tree in level order
- 0 ≤ the number of nodes ≤ 6000
- −100 ≤ Node.val ≤ 100
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* // Definition for a _Node.
* function _Node(val, left, right, next) {
* this.val = val === undefined ? null : val;
* this.left = left === undefined ? null : left;
* this.right = right === undefined ? null : right;
* this.next = next === undefined ? null : next;
* };
*/
/**
* @param {_Node} root
* @return {_Node}
*/
function connect(root) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more breadth-first search (bfs) problems
- 637Average of Levels in Binary TreeEasysolve
- 102Binary Tree Level Order TraversalMediumsolve
- 199Binary Tree Right Side ViewMediumsolve
- 994Rotting OrangesMediumsolve
- 1091Shortest Path in Binary MatrixMedium
- 841Keys and RoomsMediumsolve
- 103Binary Tree Zigzag Level Order TraversalMediumsolve
- 909Snakes and LaddersMediumsolve
- 433Minimum Genetic MutationMediumsolve
- 127Word LadderHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.