问题是我的链接队列列表没有合作。我已经盯着这一段时间,但无法弄清楚为什么我的优惠没有通过。
第一组代码在MyBST中。具有左和右元素的节点标记为TreeNodes。我创建了一个TreeNodes的Linked Queue,希望它们在通过队列时保留它们的左/右指针。我现在要发表评论......
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。 null是从我试图查看队列时开始的。