Created
December 21, 2023 21:39
-
-
Save optimistiks/1f757a3cc8698f101a5dace2cbfab8bc to your computer and use it in GitHub Desktop.
Given a perfect binary tree, where each node contains an additional pointer called next. This pointer is initially set to NULL for all nodes. Your task is to connect all nodes of the same hierarchical level by setting the next pointer to its immediate right node. The next pointer of the rightmost node at each level is set to NULL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function populateNextPointers(root) { | |
// we traverse the tree level by level by using two variables, | |
// left and current | |
// left is always the leftmost element of the current level, | |
// current starts the same as left, but moves right along the level | |
// as soon as current has nowhere to move, we shift level by shifting left down one level, and setting current to the same as left | |
// so the algorithm is | |
// root is left, current | |
// current.left.next = current.right | |
// current.next is null, shift level | |
// make root.left next, current | |
// current.left.next = current.right | |
// current.next is not null | |
// so current.right.next = current.next.left | |
// make current current.next | |
// current.left.next = current.right | |
// current.next is now null, shift level | |
let left = root; | |
let current = root; | |
while (left) { | |
if (current.left) { | |
current.left.next = current.right; | |
} | |
if (current.next) { | |
if (current.right) { | |
current.right.next = current.next.left; | |
} | |
current = current.next; | |
} else { | |
left = left.left; | |
current = left; | |
} | |
} | |
return root; | |
} | |
export { populateNextPointers }; | |
// tc: O(n) | |
// sc: O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment