MrainW's Home

All things come to those who wait!

0%

LeetCode 117. Populating Next Right Pointers in Each Node II

Question

Given a binary tree

1
2
3
4
5
6
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

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

  • Solution1
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
class Solution {
public Node connect(Node root) {
Node dummyHead = new Node(0); // this head will always point to the first element in the current layer we are searching
Node pre = dummyHead; // this 'pre' will be the "current node" that builds every single layer
Node real_root = root; // just for return statement

while(root != null){
if(root.left != null){
pre.next = root.left;
pre = pre.next;
}
if(root.right != null){
pre.next = root.right;
pre = pre.next;
}
root = root.next;
if(root == null){ // reach the end of current layer
pre = dummyHead; // shift pre back to the beginning, get ready to point to the first element in next layer
root = dummyHead.next; ;//root comes down one level below to the first available non null node
dummyHead.next = null;//reset dummyhead back to default null
}
}
return real_root;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(1)

Welcome to my other publishing channels