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 traversed i.e. linearly, binary tree has several ways to traverse all nodes e.g. preorder, postorder and inorder. But, 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 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 is 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, determine the type of algorithms. In PreOrder, you visit the root or node first, followed by left subtree and then right subtree, but in 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, its preOrder, if you visit the root second its inOrder and if you visit the root third, or last, its post order. See apart from these there are more sophisticated algorithms to traverse a binary tree, see Introduction to Algorithms to learn more about different types of tree e.g. self-balanced trees and other tree algorithms e.g. 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 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 left and right node. This is where recursion comes into play as shown in 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 a good book on data structure and algorithm to learn various ways to convert a recursive algorithm to iterative one e.g. one way to convert a recursive algorithm to iterative one is by using an explicit Stack, Introduction to Algorithm by Thomas H. Cormen is a wonderful book to learn algorithms.

binary tree preorder traversal in Java using recursion



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 represent a binary tree. It consists a TreeNode called root, which is the starting point of traversal in a binary tree. The root then refers to other tree nodes via left and right links.

The logic of pre-order traversal is coded on preOrder(TreeNode node) method. The recursive algorithm first visits the node e.g. it prints it the value then recursive call 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 a nice diagram which also shows how pre-order algorithm traverse a binary tree:

binary tree preorder traversal in Java


PreOrder traversal in Java
/*
 * 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 pre-order traversal and in last on 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 data structure and algorithms tutorials for Java Programmers
  • How to reverse a linked list in Java without recursion? (solution)
  • How to implement binary search algorithm in Java? (solution)
  • How to reverse an array in place in Java? (solution)
  • 10 Algorithm books Every Programmer Should Read (list)
  • How to implement Insertion sort in Java? (solution)
  • How to implement Quicksort algorithm in Java? (solution)
  • How to find the length of singly linked list in Java? (solution)
  • How to find the missing number in an array of 1 to 100? (solution)
  • How to find all pairs on integer array whose sum is equal to given a number? (solution)
  • 15 frequently asked data structure and algorithm Interview Questions (list)
  • 5 Books to learn data structure and algorithms in Java? (books)


No comments:

Post a Comment