级别顺序树遍历

时间:2010-10-28 15:21:48

标签: java algorithm binary-tree

我正在尝试编写一个方法,该方法将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'只会向右分支。因此,在根目录下一级后,永远不会存储某些值。我希望这很清楚,任何帮助都非常感谢。谢谢。

1 个答案:

答案 0 :(得分:1)

不是将边缘实现为值的队列,而是将其实现为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
  }

当你拥有它时,你不必同时保持tLtR指针,无论如何我认为这是一个有缺陷的方法。

链接

相关问题