# LeetCode Problem: Populating Next Right Pointers in Each Node II

By | 2012 年 12 月 24 日

The code in the previous article LeetCode Problem: Populating Next Right Pointers in Each Node, Level traversal of binary tree is also adapted to this situation.

Populating Next Right Pointers in Each Node II
Follow up for problem “Populating Next Right Pointers in Each Node”.
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,

```         1
/  \
2    3
/ \    \
4   5    7
```

After calling your function, the tree should look like:

```         1 -> NULL
/  \
2 -> 3 -> NULL
/ \    \
4-> 5 -> 7 -> NULL
```

## 3 thoughts on “LeetCode Problem: Populating Next Right Pointers in Each Node II”

1. uniEagle Post author

Yes,For the constant extra space, I can not figure out how to do it.
Because, traversal a tree, we need at least log(n) space to do it. How we can travel a tree in constant space?

1. bangbing

You don’t need log(n) EXTRA SPACE to traverse a tree. EXTRA SPACE means anything like queue/stack/vector/recursion to store temporary data. For this problem, definitely a constant space solution exists.

This is essential a level order traversal problem. Assume you have already connect level i, which means you can traverse level i from left to right using the next pointer, then you can connect level i+1 (the level below) along the way.