/**
* 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;
Queue<TreeLinkNode> qCur = new LinkedList<>();
Queue<TreeLinkNode> qNew = new LinkedList<>();
Queue<TreeLinkNode> qTemp;
qCur.offer(root);
while(!qCur.isEmpty()) {
while(!qCur.isEmpty()) {
TreeLinkNode temp = qCur.poll();
if(!qCur.isEmpty()) {
temp.next = qCur.peek();
} else {
temp.next = null;
}
if(temp.left != null) {
qNew.offer(temp.left);
}
if(temp.right != null) {
qNew.offer(temp.right);
}
}
qTemp = qCur;
qCur = qNew;
qNew = qTemp;
}
}
}
Populating Next Right Pointers in Each Node II
最新推荐文章于 2020-11-14 09:32:10 发布