代码:
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode levelHead=root;
while(levelHead!=null){ // exactly the same with while(!currLevel.isEmpty()){...}
TreeLinkNode curr=levelHead; // always have the variable recording the head of the level
while(curr!=null){ // if there is any node on this level, BFS
if(curr.left!=null) curr.left.next=curr.right;
if(curr.right!=null && curr.next!=null) curr.right.next=curr.next.left;
curr=curr.next; // move to the right on the same level. 在第一层没有发生,因为只有一个节点,第一个也是最后一个。这个递归是走到每一层的最后一个。
}
levelHead=levelHead.left; // move from the first node in this level to the next level.
}
}
}
// 这道题和 level traversal类似,但是在数据结构上 和输入输出上还是有挺大差别,两题的代码中可以找到对应逻辑,比如while()之类的,所以在generalize 两者还是可以的。但是!!在具体操作上还是应该把这题作为特例。
// 其实每一层的遍历对该层都没有进行处理,只是走完该层,同时把下一层的各个相邻节点连接起来!有点意思,自身不做处理,处理下一层!!怎么实现?从root开始啊,第一层只有一个节点,所以没有next,但是root有左右子节点,这样就可以把第2层链接起来了。下一个循环到第二层,过一遍,把第3层链接起来了,再进入第3层。 所以是 把下一层链接好了,再进入下一层,层与层之间的联系就是通过left,right实现的,同层之间的联系是通过next是实现的,单向实现!
// 这和我们之前的 level traversal是不是确实不一样。不需要额外的空间。