Leetcode 117. Populating Next Right Pointers in Each Node II
Given a binary tree:
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.
Example:
Input: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
Output: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$ref":"4"},"right":null,"val":4},"next":{"$ref":"5"},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"5"},"val":3},"next":null}
Here is a solution using the described strategy of level order traversal with a queue:
#include <queue>
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
class Solution {
public:
Node* connect(Node* root) {
if (!root) return root;
std::queue<Node*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
Node* prev = nullptr;
for (int i = 0; i < size; ++i) {
Node* curr = q.front();
q.pop();
if (prev) {
prev->next = curr;
}
prev = curr;
if (curr->left) {
q.push(curr->left);
}
if (curr->right) {
q.push(curr->right);
}
}
// The last node of the current level should point to NULL
if (prev) {
prev->next = NULL;
}
}
return root;
}
};
This is because each node is processed exactly once in the level-order traversal.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?