Java创建一个队列:
Queue<Node> queue = new LinkedList<Node>();
队列的常用方法:
- queue.offer(root);
- 添加值进队列
- Node node = queue.poll();
- 弹出值
- queue.addAll(node.children);
- 将孩子节点的所有值都添加
接上篇leecode专题附上使用队列的解题方案:
【leecode-101】判断一颗二叉树是否轴对称_hah杨大仙的博客-CSDN博客
// 方式二,队列循环判断
public boolean isSymmetric(TreeNode root){
Queue<TreeNode> q = new LinkedList<TreeNode>();
TreeNode r = root.right;
TreeNode l = root.left;
if(root==null || (r==null&&l==null)){
return true;
}
q.offer(r);
q.offer(l);
while(!q.isEmpty()){
r=q.poll();
l=q.poll();
if(r==null&&l==null){
continue;
}
if(r==null||l==null || (r.val!=l.val)){
return false;
}
q.offer(r.right);
q.offer(l.left);
q.offer(r.left);
q.offer(l.right);
}
return true;
}
..
Thanks