Description
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:
Note:
- You may only use constant extra space.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
解法
116题的改版,只需要在连接前遍历父节点层找到下一个邻接节点即可,注意递归的时候应该先递归右边的部分,确保右边的next已经完全连上了,否则会导致结果的错误(在这个坑里WA了半天才想明白)。
具体代码如下:
1 | class Solution { |