Last updated
Was this helpful?
Last updated
Was this helpful?
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 toNULL
.
Initially, all next pointers are set toNULL
.
Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
Example:
Given the following binary tree,
After calling your function, the tree should look like:
A very concise and clear level-order traversal (@davidtan1890):
Iterative
用一个 dummy node nextHead
来代表指向下一行的开头节点,并用一个tail
指针初始化为nextHead
作为下一行进行连接的指针,当前行则用curr
表示,当curr.left
或者curr.right
不为null,就将tail.next指向它们,并且继续移动tail = tail.next
一行遍历结束,也就是curr = null
,就要重新赋值nextHead.next
给curr
,因为nextHead.next
指向的是下一行的第一个node;
这里要注意nextHead.next = null;
因为如果不舍为空,那么循环就无法结束。
Iterative - O(n) time, O(1) space
Recursive