如何解决使用两个队列的级别顺序遍历二叉树
密码问题:https://leetcode.com/problems/binary-tree-level-order-traversal/
我有两个队列,在将元素添加到第二个队列(q2)的同时清空第一个队列(q),这样我就可以获取关卡。当第一个队列为空时,我将其传递给函数以创建该级别的ArrayList并添加到我的结果值中,如果q2为空,则表示未添加任何内容,因此我们可以跳出循环并返回函数。我必须手动添加第一个节点。问题在于仅添加了中间级别,而没有添加其他级别。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val,TreeNode left,TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) {
return null;
}
List<List<Integer>> returnList = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
List<Integer> tempList = new ArrayList<>();
tempList.add(root.val);
returnList.add(tempList);
while(true) {
Queue<TreeNode> q2 = new LinkedList<>();
while(!q.isEmpty()) {
TreeNode node = q.remove();
if(node.left != null) {
q2.add(node.left);
}
if(node.right != null) {
q2.add(node.right);
}
}
if(q2.isEmpty()) {
break;
}
q = q2;
addList(returnList,q2);
}
return returnList;
}
public static void addList(List<List<Integer>> returnList,Queue<TreeNode> q2) {
List<Integer> tempList = new ArrayList<>();
int size = q2.size();
for(int i = 0; i < size; i++) {
int val = q2.remove().val;
System.out.println(val);
tempList.add(val);
}
returnList.add(tempList);
}
}
解决方法
问题与这段代码有关:
q = q2;
addList(returnList,q2);
函数addList
将清空给定队列q2
,并在其上调用remove
。由于q
已成为 same 队列的引用,因此您已清空q
,因此外循环的下一次迭代将不会进入内循环并退出带有break
的外部循环。
为避免发生这种情况,请确保未在remove
上执行q
调用:进行复制:
q = new LinkedList<>(q2);
addList(returnList,q2);
或者,或者:
q = q2;
addList(returnList,new LinkedList<>(q2));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。