这是“每个节点的右向指针”问题的进阶。
如果给定的树可以是任何二叉树,该怎么办?你以前的解决方案仍然有效吗?
注意:
你只能使用恒定的空间。
例如,
给定以下二叉树,
1
/
2 3
/
4 5 7
调用你的函数后,树应该看起来像这样:
1 -> NULL
/
2 -> 3 -> NULL
/
4-> 5 -> 7 -> NULL
详见:https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/description/
Java实现:
/**
* 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) {
if(root==null){
return;
}
LinkedList<TreeLinkNode> que=new LinkedList<TreeLinkNode>();
que.offer(root);
while(!que.isEmpty()){
//记录本层节点的个数
int size=que.size();
for(int i=0;i<size;++i){
TreeLinkNode cur=que.poll();
//最后一个节点的next是null,不做处理
if(i<size-1){
TreeLinkNode next=que.peek();
cur.next=next;
}
if(cur.left!=null){
que.offer(cur.left);
}
if(cur.right!=null){
que.offer(cur.right);
}
}
}
}
}
参考:https://segmentfault.com/a/1190000003465911