Populating Next Right Pointers in Each Node
Given a binary tree
1 | struct TreeLinkNode { |
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
.
Note:
- You may only use constant extra space.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
Example:
Given the following perfect binary tree,
1 | 1 |
After calling your function, the tree should look like:
1 | 1 -> NULL |
思路:一道看起来很有趣的题目,给树的每个节点又增加了一个节点,细心观察会发现,其实就是层序遍历的时候,我们只要在这个层序遍历的过程中给同一层的前后节点之间增加一个next的关系即可,同一层的最后一个节点赋予它next=null即可。代码如下:
1 | /** |