Java 级序树遍历
我正在尝试编写一个方法,该方法将IntTree作为参数,并以级别顺序返回一个包含IntTree值的队列。澄清一下:IntTree是以整数值作为根的树,其左、右子树都是IntTree。 关于某些方法的说明: value(t)-返回树根处的整数值 left(t)-返回左IntTree子树// 右(t)-返回右子树 这是我到目前为止的代码。我对编程相当陌生,所以如果它不是很优雅,我很抱歉Java 级序树遍历,java,algorithm,binary-tree,Java,Algorithm,Binary Tree,我正在尝试编写一个方法,该方法将IntTree作为参数,并以级别顺序返回一个包含IntTree值的队列。澄清一下:IntTree是以整数值作为根的树,其左、右子树都是IntTree。 关于某些方法的说明: value(t)-返回树根处的整数值 left(t)-返回左IntTree子树// 右(t)-返回右子树 这是我到目前为止的代码。我对编程相当陌生,所以如果它不是很优雅,我很抱歉 public static QueueList levelOrder(IntTree t) { //returns
public static QueueList levelOrder(IntTree t) {
//returns a QueueList with the values in level order
Object val;
QueueList q = new QueueList(); //temp queueList
QueueList theta = new QueueList(); //the QueueList which will eventually be printed
if (isEmpty(t)) {
return theta; //possible problem here
} else {
IntTree tL = left(t); //using for possible updating. probably won't work
IntTree tR = right(t);
q.enqueue(value(t)); //enqueue the root of the tree
while (!q.isEmpty()) {
val = q.dequeue(); //pop off the top element for printing
theta.enqueue(val); // put the element in the queue to be printed
if (tL != null) {
q.enqueue(value(tL)); //if the left isn't null, enqueue the lefts
tL = left(tL); //this will only branch left
}
if (tR != null) { //if the right isn't null, enqueue the rights
q.enqueue(value(tR));
tR = right(tR); //this will only branch right
}
}
}
return theta; //returns a queue with values in order
}
我编写了tL和tR变量,因为如果我编写类似于“if(left(t)!=null)”的内容,我将以无限递归结束,因为“t”从未更新过。此代码的问题是“tL”只会向左分支,“tR”只会向右分支。因此,在根下一级之后,某些值将永远不会被存储。我希望这是清楚的,任何帮助都是非常感谢的。谢谢。与其将边缘实现为值队列,不如将其实现为IntTrees(节点)队列。这将大大简化您的逻辑
while (!q.isEmpty()) {
IntTree node = q.dequeue(); //pop off the top element
theta.enqueue(value(node)); // put the element in the queue to be printed
//enqueue the children
IntTree left = left(node);
if ( left != null ) {
q.enqueue(left);
}
//...similar for right
}
当你有了它,你就不必并行地维护tL
和tR
指针,我认为这是一种有缺陷的方法
链接