Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

How to implement PreOrder traversal of Binary Tree in Java - Example Tutorial

The easiest way to implement the preOrder traversal of a binary tree in Java is by using recursion. The recursive solution is hardly 3 to 4 lines of code and exactly mimic the steps, but before that, let's revise some basics about a binary tree and preorder traversal. Unlike array and linked list which have just one way to traverse, I mean linearly, the binary tree has several ways to traverse all nodes because of its hierarchical nature like level order, preorder, postorder, and in order. Tree traversal algorithms are mainly divided into two categories, the depth-first algorithms, and breadth-first algorithms. In depth-first, you go deeper into a tree before visiting the sibling node, for example, you go deep following the left node before you come back and traverse the right node.

On breadth-first traversal, you visit the tree on its breadth i.e. all nodes of one level are visited before you start with another level top to bottom. The PreOrder, InOrder, and PostOrder traversals are all examples of depth-first traversal algorithms.

While traversing a tree, you need to visit three elements, root node, left subtree, and right subtree. The order in which you visit these three nodes determines the type of algorithms.

In PreOrder, you visit the root or node first, followed by the left subtree and the right subtree, but in the post order algorithm, you visit the root node at the last.

Now you should get the point that why this algorithm is called pre-order? well, because the order is determined by root, if you visit the root first, it's preOrder, if you visit the root second it's in inOrder, and if you visit the root third, or last, its post-order traversal.

Apart from these three basic traversal algorithms, there are also more sophisticated algorithms to traverse a binary tree, you can check a comprehensive course like  Data Structures and Algorithms: Deep Dive Using Java to learn more about different types of trees e.g. self-balanced trees and other tree algorithms like level order traversal.





Binary Tree PreOrder traversal in Java using Recursion

As I told you before, the based algorithms are naturally recursive because a binary tree is a recursive data structure. In order to visit the binary tree in preorder you can follow the following steps:
  1. visit the node or root
  2. visit the left tree
  3. visit the right tree
In order to visit the left and right subtree, you can just call the same method with the left and right nodes. This is where recursion comes into play as shown in the following code snippet:

private void preOrder(TreeNode node) {
    if (node == null) {
      return;
    }
    System.out.printf("%s ", node.data);
    preOrder(node.left);
    preOrder(node.right);
}
You can see the code is exactly written as the steps shown above, except the base case which is very important in a recursive algorithm you can read the code like steps. This is the power of recursion, it makes code concise and highly readable.

Though, you should not use recursion in production because it's prone to StackOverFlowError if a binary tree is too big to fit in memory. You should use an iterative algorithm in production to solve problems as seen earlier in Fibonacci and Palindrome problems.

You can also refer to a good course on data structure and algorithms to learn various ways to convert a recursive algorithm to an iterative one like one way to convert a recursive algorithm to an iterative one is by using an explicit Stack,  Algorithms, and Data Structures - Part 1 and 2 courses on Pluralsight. is a nice course to learn algorithms and Fundamental data structure.

How to implement PreOrder traversal of Binary Tree in Java - Example Tutorial






Java Program to implement PreOrder traversal of Binary Tree

Here is our sample program to visit all nodes of a binary tree in preorder. In this program, we have a class called BinaryTree, which represents a binary tree. It consists of a TreeNode called root, which is the starting point of traversal in a binary tree. The root then refers to other tree nodes via the left and right links.

The logic of pre-order traversal is coded on the preOrder(TreeNode node) method. The recursive algorithm first visits the node e.g. it prints the value then recursive calls the preOrder() method with left subtree, followed by right subtree.

I have another method preOrder() just to encapsulate the logic and make it easier for clients to call this method

Here is also a nice diagram that also shows how the pre-order algorithm traverses a binary tree. If you like books, you can also see Introduction to Algorithms by Thomas H. Corman to learn more about binary tree algorithms.


binary tree preorder traversal in Java



PreOrder traversal in Java- Coding

Finally here is our Java program to traverse a binary tree in pre-order. The nodes are printed accordingly.
/*
 * Java Program to traverse a binary tree using PreOrder traversal. 
 * In PreOrder the node value is printed first, followed by visit
 * to left and right subtree. 
 * input:
 *     A
 *    / \
 *   B   E
 *  / \   \
 * C   D   F
 * 
 * output: A B C D E F 
 */

public class Main {

  public static void main(String[] args) throws Exception {

    // construct the binary tree given in question
    BinaryTree bt = new BinaryTree();
    BinaryTree.TreeNode root = new BinaryTree.TreeNode("A");
    bt.root = root;
    bt.root.left = new BinaryTree.TreeNode("B");
    bt.root.left.left = new BinaryTree.TreeNode("C");

    bt.root.left.right = new BinaryTree.TreeNode("D");
    bt.root.right = new BinaryTree.TreeNode("E");
    bt.root.right.right = new BinaryTree.TreeNode("F");

    // visitng nodes in preOrder traversal
    System.out.println("printing nodes of a binary tree in preOrder 
                        using recursion");
    bt.preOrder();

  }

}

class BinaryTree {
  static class TreeNode {
    String data;
    TreeNode left, right;

    TreeNode(String value) {
      this.data = value;
      left = right = null;
    }

    boolean isLeaf() {
      return left == null ? right == null : false;
    }

  }

  // root of binary tree
  TreeNode root;

  /**
   * Java method to print tree nodes in PreOrder traversal
   */
  public void preOrder() {
    preOrder(root);
  }

  /**
   * traverse the binary tree in PreOrder
   * @param node - starting node, root
   */
  private void preOrder(TreeNode node) {
    if (node == null) {
      return;
    }
    System.out.printf("%s ", node.data);
    preOrder(node.left);
    preOrder(node.right);
  }

}
Output
printing nodes of a binary tree in preOrder using recursion
A B C D E F 

You can see that nodes are printed as per the pre-order traversal algorithm. The root node is always get printed first in the pre-order traversal and in last on the post-order traversal algorithm.

That's all about how to traverse a binary tree in PreOrder traversal in Java. The recursive algorithm is very simple and hardly required 3 to 4 lines of code. Just remember that in preOrder traversal you visit node first, followed by left subtree, and finally right subtree.


Other Binary Tree Tutorials and Interview Questions
If you like this article and would like to try out a couple of more challenging programming exercises, then take a look at the following programming questions from various Interviews :
  • 50+ Data Structure and Algorithms Problems from Interviews (list)
  • 5 Books to Learn Data Structure and Algorithms in-depth (books
  • How to print all leaf nodes of a binary tree in Java? (solution)
  • 7 Courses to learn Data Structure and Algorithms (courses)
  • How to implement a binary search tree in Java? (solution)
  • 7 Free Books to learn Algorithms and Data Structure? (books)
  • How to implement a recursive preorder algorithm in Java? (solution)
  • 20+ Array-Based Coding Problems for programmers (list)
  • Recursive Post Order traversal Algorithm (solution)
  • How to print leaf nodes of a binary tree without recursion? (solution)
  • 75+ Coding Interview Questions for Programmers (questions)
  • Iterative PreOrder traversal in a binary tree (solution)
  • 20+ Binary tree-based coding problems for programmers (list)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • 100+ Data Structure Coding Problems from Interviews (questions)
  • Recursive InOrder traversal Algorithm (solution)
  • Postorder binary tree traversal without recursion (solution)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
Thanks for reading this coding interview question so far. If you like this Binary search tree Post order traversal tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these best data structure courses in Java. It contains the best courses Java programmers can take to build their DS and Algo skills. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.