-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopulating-next-right-pointers-ii.js
More file actions
71 lines (56 loc) · 1.75 KB
/
populating-next-right-pointers-ii.js
File metadata and controls
71 lines (56 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Problem: Populating Next Right Pointers in Each Node II
* Link: https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
* Difficulty: Medium
*
* Populate each next pointer to point to its next right node.
* If there is no next right node, set it to NULL. Tree may not be perfect.
*
* Time Complexity: O(n)
* Space Complexity: O(1) using the established next pointers
*/
// JavaScript Solution - BFS with constant space
function connect(root) {
if (!root) return root;
let current = root; // current level's starting node
while (current) {
let dummy = { next: null }; // dummy node for next level's linked list
let tail = dummy; // tail of next level's linked list
// Traverse current level using next pointers
let node = current;
while (node) {
if (node.left) {
tail.next = node.left; // connect left child
tail = tail.next;
}
if (node.right) {
tail.next = node.right; // connect right child
tail = tail.next;
}
node = node.next; // move to next node in current level
}
current = dummy.next; // move to next level
}
return root;
}
module.exports = connect;
/* Python Solution:
def connect(root):
if not root:
return root
current = root
while current:
dummy = Node(0) # dummy head for next level
tail = dummy
node = current
while node:
if node.left:
tail.next = node.left
tail = tail.next
if node.right:
tail.next = node.right
tail = tail.next
node = node.next # traverse current level
current = dummy.next # move to next level
return root
*/