简体   繁体   中英

Preorder printing Binary Tree with indentations

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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