Preorder printing Binary Tree with indentations

眉间皱痕 提交于 2019-12-08 12:41:46

问题


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());
      }
}

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.


回答1:


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 + "  ")
}


来源:https://stackoverflow.com/questions/13424656/preorder-printing-binary-tree-with-indentations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!