二叉树-广度优先-队列
给定一个二叉树
class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) { val = x; }
}
- 你只能使用常量级的额外内存空间
- 可以假设给出的二叉树是一个完美的二叉树(即,所有叶子节点都位于同一层,而且每个父节点都有两个孩子节点)。
1↵ / ↵ 2 3↵ / / ↵ 4 5 6 7↵
调用完你给出的函数以后,这颗二叉树应该 变成:
1 -> NULL↵ / ↵ 2 -> 3 -> NULL↵ / / ↵ 4->5->6->7 -> NULL
队列(Queue)用法
https://www.runoob.com/java/data-queue.html、https://www.cnblogs.com/lemon-flm/p/7877898.html
队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作。
LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞remove、element、offer 、poll、peek 其实是属于Queue接口。
链接:https://www.nowcoder.com/questionTerminal/fdbd05d647084fcf9be78444e231998b?f=discussion
来源:牛客网
辅助队列
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null)
return;
Queue<TreeLinkNode> q=new LinkedList<TreeLinkNode>();
q.add(root);
q.add(null);
while(!q.isEmpty()){
TreeLinkNode node=q.remove();
if(!q.isEmpty()){
node.next=q.peek();
if(node.left!=null)
q.add(node.left);
if(node.right!=null)
q.add(node.right);
if(q.peek()==null){
q.add(null);
q.remove();
}
}
}
}
}
我的理解:
1.把TreeLinkNode加入队列,把null加入队列
2.remove移除第一个,返回移除的信息AA用于接下来的操作。
3.若队列不为空,则AA的next为当前队列的第一个。
4.若左孩子不为空,则加入队列。
5.若右孩子不为空,则加入队列。
6.若队列第一个元素为null,则删除,并在队列后再加一个null;
。。。
这样就全部处理完了。
链接:https://www.nowcoder.com/questionTerminal/fdbd05d647084fcf9be78444e231998b?f=discussion
来源:牛客网
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null)return;
while(root.left!=null){
TreeLinkNode node=root;
while(node!=null){
node.left.next=node.right;
if(node.next!=null)node.right.next=node.next.left;
node=node.next;
}
root=root.left;
}
}
}
这个是两个while循环来处理的。

浙公网安备 33010602011771号