繁体   English   中英

层次树遍历

[英]Level-order tree traversal

我正在尝试编写一个将IntTree作为参数并按级别顺序返回带有IntTree值的Queue的方法。 需要说明的是:IntTree是一棵以整数值为根的树,并具有IntTree作为其左和右子树。 关于某些方法的注释:value(t)-返回树根的整数值left(t)-返回左IntTree子树// right(t)-返回右子树

这是我到目前为止的代码。 我是编程新手,所以如果它不是很优雅,我感到很抱歉。

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”只会向右分支。 因此,在根目录下一级之后,将永远不会存储某些值。 我希望这一点很清楚,任何帮助都将不胜感激。 谢谢。

与其将条纹实现为值队列,不如将其实现为IntTree(节点)的队列。 这将极大地简化您的逻辑。

  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
  }

有了这个,您不必并行维护tLtR指针,我想无论如何这都是一种有缺陷的方法。

链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM