java - BST 中的水平遍历。队列不合作
问题描述
问题是我的链接队列列表不合作。我已经盯着这个看了一段时间,不明白为什么我的报价没有通过。
第一组代码在 MyBST 中。具有左右元素的节点被标记为 TreeNodes。我创建了一个 TreeNode 的链接队列,希望它们在通过队列时保留左/右指针。我现在要进行在线评论...
private void traversalBreadth(TreeNode<E> current)
{
if(current==null)return;
MyLinkedQueue<TreeNode<E>> q = new MyLinkedQueue<TreeNode<E>>();
q.offer(current);//goes through fine and is able to start the while loop
//with no issues.
while(q.isEmpty()==false)
{
current= (TreeNode<E>) q.poll();//so that the loop prints the current element.
System.out.println(current.element); //where each level will print
if(current.left!=null)
{
//Problem is here. I am offering the left element of my BST but nothing is actually in the queue.
q.offer(current.left);
//I tried printing current.left.element and current.right.element and they always work with no issue. i am not sure why i cannot offer it to my queue.
System.out.println(q.peek());//checking to see if anything here but nothing.
}
if(current.right!=null)
{
q.offer(current.right);
}
}
}
链接队列以防万一出现问题:
package HW8;
public class MyLinkedQueue<E> {
QueueNode<E> head,tail;
MyLinkedQueue(){
}
MyLinkedQueue(E[] objects)
{
for(E e: objects)
offer(e);
}
class QueueNode<E>
{
E element;
QueueNode <E> next;
public QueueNode(E element){
this.element=element;
}
}
E poll() {
if(head==null) return null;
QueueNode<E> tmp = head;
head = head.next;
//head.previous = null;
return tmp.element;
}
E peek() {
if(head==null) return null;
return head.element;
}
void offer(E e) {
QueueNode<E> newNode = new QueueNode<>(e);
if(tail==null)
{
head=tail=new QueueNode<>(e);
}
else{
tail.next = newNode;
tail = newNode;
}
}
boolean isPalin() {
if(head!=tail)
{
return false;
}
else {
boolean first = true;
QueueNode<E> current = head;
QueueNode<E> backwards = tail;
while(current!=tail) {
current = current.next;
}
}
return false;
}
boolean isEmpty() {
if(head==null||tail==null)
return true;
else
return false;
}
}
Edit1:主要代码只是
Integer a[] = { 22, 3, 8, 16, 64, 7, 18 ,
-3, 23, -10, -1, 25, 20, 9};
MyBST test = new MyBST(a);
test.breadthOrder();
它输出 22、3、null。空值来自我尝试查看队列时。
解决方案
推荐阅读
- javascript - Serverless-webpack 部署脚本在 Webpack 4.8 中“挂起”,而在 3.12 中运行正常。
- javascript - 使用带有 nodejs 的 tesseract 获取无效回调
- java - 如何使用 JPA EclipseLink 启用 Unicode 编码?
- git - 我需要“Git”来安装 Apache Spark
- umbraco - Umbraco 包在部署后出现问题
- azure-devops - VSTS“Visual Studio 测试”任务找不到 .Net Core dll 的测试
- bluetooth-lowenergy - 蓝牙 LE Gatt 服务器特征值在 Tizen 3.0.0.2 上始终为 NULL
- intellij-idea - KotlinJS 1.2 不支持 Launch-Coroutine 和其他?
- android - “无法在设备上安装应用程序”错误消息
- node.js - 通过节点 js 脚本执行 docker 命令