【问题标题】:Print a Tree By Level (with a simple method) [duplicate]按级别打印树(使用简单的方法)[重复]
【发布时间】:2014-07-27 02:40:33
【问题描述】:

PS:这不是家庭作业。而且我不明白其他问题的答案,否则我不会打开一个新的......

我正在尝试打印这棵树:

            3
          /   \
        7       2
      /   \       \
    0       9      11
  /   \           /  \
1       2       6      4

作为级别命令输出:

3
7 2
0 9 11
1 2 6 4

问题是我的代码只能打印这样的树:3 7 2 0 9 11 1 2 64,这与最后一个数字相同,但没有段落或'\ n'。我似乎找不到一种简单的方法来做到这一点(最好不使用 foreach)。有人告诉我我应该在树上创建一个变量:'level',用于分类节点所在的级别,但我怎么才能对级别进行分类呢? 你能帮帮我吗?

public void largura() { //just an auxiliar method to call 'larguras'
   larguras(root);
   System.out.println();
}

private void larguras(Node t) {
   LinkedList<Node> f = new LinkedList<Node>();
   Node r;
   f.add(t);

   while (!f.isEmpty()) {
       r=f.remove();
       if (r!=root) System.out.print(" ");
       System.out.print(r.value);
       if (r.left != null) f.add(r.left);
       if (r.right != null) f.add(r.right);
   }

}

【问题讨论】:

  • 让问题更简单(为自己)。如何打印具有一个节点的树?你如何打印一棵有一个根和两个孩子的树?间距是什么样的?
  • 我已经知道了。问题不在于那个,而在于试图找出特定节点属于哪个级别!
  • 真的不清楚你为什么说这不是this 的重复——据我所知,你问的是完全相同的问题。如果您有不同的、更具体的问题,请提出不同的问题。否则,我建议您研究其他问题的答案,直到您理解为止。

标签: java


【解决方案1】:

嗯...这样的东西有用吗?

 //Prints the tree in level order
  public void printTree(){
    printTree(root);
  }

 public void printTree(TreeNode tmpRoot){

//If the first node isn't null....continue on
if(tmpRoot != null){

    Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); //Queue that holds the nodes on the current level
    Queue<TreeNode> nextLevel = new LinkedList<TreeNode>();     //Queue the stores the nodes for the next level

    int treeHeight = height(tmpRoot);     //Stores the height of the current tree
    int levelTotal = 0;  //keeps track of the total levels printed so we don't  pass the height and print a billion "null"s

    //put the root on the currnt level's queue
    currentLevel.add(tmpRoot);

    //while there is still another level to print and we haven't gone past the tree's height
    while(!currentLevel.isEmpty()&& (levelTotal< treeHeight)){

        //Print the next node on the level, add its childen to the next level's queue, and dequeue the node...do this until the current level has been printed
        while(!currentLevel.isEmpty()){

            //Print the current value
            System.out.print(currentLevel.peek().getValue()+" ");

            //If there is a left pointer, put the node on the nextLevel's stack. If there is no ponter, add a node with a null value to the next level's stack
            tmpRoot = currentLevel.peek().getLeft();
            if(tmpRoot != null)
                nextLevel.add(tmpRoot);
            else
                nextLevel.add(new TreeNode(null));

            //If there is a right pointer, put the node on the nextLevel's stack. If there is no ponter, add a node with a null value to the next level's stack
            tmpRoot = currentLevel.remove().getRight();
            if(tmpRoot != null)
                nextLevel.add(tmpRoot);
            else
                nextLevel.add(new TreeNode(null));

        }//end while(!currentLevel.isEmpty())

        //populate the currentLevel queue with items from the next level
        while(!nextLevel.isEmpty()){
            currentLevel.add(nextLevel.remove());
        }

        //Print a blank line to show height
        System.out.println("");

        //flag that we are working on the next level
        levelTotal++;

    }//end while(!currentLevel.isEmpty())

}//end if(tmpRoot != null)

}//end method printTree

public int height(){
    return height(getRoot());
  }

public int height(TreeNode tmpRoot){

if (tmpRoot == null)
    return 0;
int leftHeight = height(tmpRoot.getLeft());
int rightHeight = height(tmpRoot.getRight());

if(leftHeight >= rightHeight)
    return leftHeight + 1;
else
    return rightHeight + 1;

或者可能是这样的:

 public void BFSPrint()
{
    Queue<Node> q = new LinkedList<Node>();
    q.offer(root);
    BFSPrint(q);
}

private void BFSPrint(Queue<Node> q)
{
if(q.isEmpty())
    return;
int qLen = q.size(),i=0;
 /*limiting it to q size when it is passed, 
   this will make it print in next lines. if we use iterator instead, 
   we will again have same output as question, because iterator 
   will end only q empties*/
while(i<qLen) 
    {
    Node current = q.remove();
    System.out.print(current.data+" ");
    if(current.left!=null)
        q.offer(current.left);
    if(current.right!=null)
        q.offer(current.right);
    i++;
}
System.out.println();
BFSPrint(q);

}

基本上你正在做这样的事情: http://leetcode.com/2010/09/printing-binary-tree-in-level-order.html

上面的代码不适用于超过 3 个级别的树,您需要自己弄清楚。 @commenter / -1'er 我举了一个例子,这样他们就可以玩了。这似乎是家庭作业或示例练习,我发现玩代码本身对学习更有帮助。这就是为什么我给出了多个实现。

【讨论】:

  • 全部代码没有解释有点……郁闷。
  • 一点解释和一些伪代码将比这么长的示例更有帮助。编写解决方案也有助于 OP 学习。
  • 在我看来这是一个家庭作业问题,所以我不想在潜在的学术不诚实的情况下给出完整的解决方案。但我提供了 3 个强有力的例子进行比较。
  • 这不是作业,我什至没有学习。
猜你喜欢
  • 2023-03-29
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多