Binary Tree Preorder Traversal in Java

Binary Tree Preorder Traversal in Java

Preorder traversal of Binary Tree is very popular interview question.
In Preorder traversal, Root node is read first then Left child and at last Right child. There are 2 ways to read Preorder traversal,
1. Recursive Preorder traversal of Binary tree.
2. Iterative Preorder traversal of Binary tree.
Preorder traversal example.

Preorder Traversal

There are many ways to traverse a Binary Tree like, Preorder traversal, Inorder traversal, Postorder traversal, Spiral order traversal, Vertical order traversal etc.

In this post, we will focus on Preorder Traversal of Binary Tree


Preorder traversal: To traverse a binary tree in Preorder,
1. Visit the root node and print data of that node. 
2. Traverse the Left subtree.
3. Traverse the Right subtree. 

Therefore, the Preorder traversal of the above sample tree will output: 45  25  15  35  75.

Let's see Preorder traversal step by step.

Preorder Traversals Java Program.

class Node{
 private int data;
 private Node left;
 private Node right;

 public Node(int data) {;

 public int getData() {
  return data;
 public void setData(int data) { = data;
 public Node getLeft() {
  return left;
 public void setLeft(Node left) {
  this.left = left;
 public Node getRight() {
  return right;
 public void setRight(Node right) {
  this.right = right;

package tree;

import java.util.LinkedList;
import java.util.Queue;

public class PreorderBinaryTreeTraversal {
 private Node rootNode;

 public static void main(String[] args) {
  new BinaryTreeTraversal();

 public PreorderBinaryTreeTraversal(){

  addNode(rootNode, 45); 
  addNode(rootNode, 25); 
  addNode(rootNode, 75); 
  addNode(rootNode, 15); 
  addNode(rootNode, 35); 
  System.out.println("\nPre Order Traversal :");
 //Preorder traversal printing. 
 private void printTreePreOrder(Node rootNode){
  System.out.print(rootNode.getData() + " ");
 private void addNode(Node rootNode, int data){
   Node temp1 = new Node(data);
   addNodeInProperPlace(rootNode, data);
 private void addNodeInProperPlace(Node rootNode, int data){ 
    addNode(rootNode.getRight(), data);
    Node temp1 = new Node(data);
  }else if(data<rootNode.getData()){
    addNode(rootNode.getLeft(), data);
    Node temp1 = new Node(data);

You may also like to see

Postorder Traversal Java Program

Zig Zag Traversal of Binary Tree. 

Boundary Traversal of binary tree. 

Print Nodes in Top View of Binary Tree

Print Nodes in Bottom View of Binary Tree.

Print a Binary Tree in Vertical Order

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment