Populating Next Right Pointers in Each Node II
Given a binary tree
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.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:

From here.
The algorithm is a BFS or level order traversal. We go through the tree level by level. node is the pointer in the parent level, tail is the tail pointer in the child level. The parent level can be view as a singly linked list or queue, which we can traversal easily with a pointer. Connect the tail with every one of the possible nodes in child level, update it only if the connected node is not nil. Do this one level by one level. The whole thing is quite straightforward.
Last updated
Was this helpful?