Java BST队列中的级别遍历不合作
问题是我的链接队列列表不配合。我已经盯着这个看了一段时间,不明白为什么我的报价没有通过 第一组代码在MyBST中。具有左侧和右侧元素的节点标记为TreeNodes。我创建了一个树节点链接队列,希望它们在遍历队列时保留左/右指针。我现在要发表在线评论Java BST队列中的级别遍历不合作,java,binary-search-tree,traversal,Java,Binary Search Tree,Traversal,问题是我的链接队列列表不配合。我已经盯着这个看了一段时间,不明白为什么我的报价没有通过 第一组代码在MyBST中。具有左侧和右侧元素的节点标记为TreeNodes。我创建了一个树节点链接队列,希望它们在遍历队列时保留左/右指针。我现在要发表在线评论 private void traversalBreadth(TreeNode<E> current) { if(current==null)return; MyLinkedQueue<TreeNode<E&g
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);
}
}
}
它输出22,3,null。空值来自我尝试查看队列时。您能提供输出吗?您还可以尝试用标准的
队列
代替您自己的实现吗?理想情况下,也提供输入。样本输出打印22、3、空。我将编辑上面我的主要代码做什么你是对的,我可以让它与队列正确运行。现在我只是想知道我的实现有什么问题。非常感谢。尝试以下操作:offer(1)、poll()、offer(2)、offer(3)
,您应该看到它不会产生您想要的结果。
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;
}
}
Integer a[] = { 22, 3, 8, 16, 64, 7, 18 ,
-3, 23, -10, -1, 25, 20, 9};
MyBST test = new MyBST(a);
test.breadthOrder();