预打印带缩进的二叉树 [英] Preorder printing Binary Tree with indentations

查看:234
本文介绍了预打印带缩进的二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对每个后续级别预打印带有缩进(3个空格)的二叉树.在这一点上,我正在使用辅助方法来递归地打印树,但是我不确定如何对缩进进行编码. 这是我到目前为止的内容:

How would one go about pre-order printing a binary tree with an indentation (3 spaces) for each subsequent level. At this point, I'm recursively printing out the tree by using a helper method, but I'm not sure how to go about coding the indentation. This is what I have so far:

public void print() {
      printPreorder(root);
      System.out.println();
}

private void printPreorder(BinaryTreenode<E> node) {
      System.out.println(node.getData() + " ");
      if (node.getLeft() != null) {
            printPreorder(node.getRight());
      }
      if (node.getRight() != null) {
            printPreorder(node.getRight());
      }
}

我的直接想法是在每次递归调用该方法时都放入一个计数器并使它递增,然后为每个增量缩进三个空格,但是我不确定这是执行此操作的最佳方法./p>

My immediate thought was to put in a counter and have it increment each time the method is recursively called, and then indent three spaces for each increment, but I'm not sure that this is the best way to do this.

推荐答案

您正在朝正确的方向前进.这是一些通用的伪代码:

You were heading in the right direction. Here's some general pseudocode:

void print(node) {
  print(node, "")
}

private void print(node, indent) {
  if(node is null) return
  output(indent + node.data)
  print(node.left, indent + "  ")
  print(node.right, indent + "  ")
}

这篇关于预打印带缩进的二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆