Tree Traversals - Depth First (Recursive Approach)
Tree is a hierarchical data structure and therefore can be traversed in more than one way unlike liner data structures. Each order of traversal has its own benefits.
Generally there are two main ways to traverse a binary tree -
1. Depth First Traversal
2. Breadth First Traversal
In this particular article we will discuss three ways to traverse a binary tree using Depth First approach. Also we can implement the traversal using either recursive approach or Iterative approach, but here we will go with recursive approach.
For Breadth First or level order Traversal visit this link - Binary Tree - Breadth First or Level Order Traversal
In Depth First traversal there are 3 ways to traverse a binary tree -
- Inorder Traversal (Left, Root, Right)
- Preorder Traversal (Root, Left, Right)
- Postorder Traversal (Left, Right, Root)
- Visit root Node
- Visit right subtree
Suppose we have a binary tree as shown in the figure below -
package ds.tree;
public class BStree {
private Node root;
public BStree(int rootData) {
this.root = new Node(rootData);
}
static class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
}
}
public void insert(int data) {
Node nNode = new Node(data);
Node root = this.root;
Node nodeB = null;
while (root != null) {
nodeB = root;
if (root.data > data) {
root = root.left;
} else {
root = root.right;
}
}
if(data < nodeB.data)
nodeB.left = nNode;
else
nodeB.right = nNode;
}
public void printInOrder() {
inOrderRec(this.root);
}
private void inOrderRec(Node root){
if(root == null)
return;
inOrderRec(root.left);
System.out.print(root.data + " ");
inOrderRec(root.right);
}
public void printPreOrder() {
preOrderRec(this.root);
}
private void preOrderRec(Node root) {
if(root == null)
return;
System.out.print(root.data + " ");
preOrderRec(root.left);
preOrderRec(root.right);
}
public void printPostOrder() {
postOrderRec(this.root);
}
private void postOrderRec(Node root) {
if(root == null)
return;
postOrderRec(root.left);
postOrderRec(root.right);
System.out.print(root.data + " ");
}
}
Now to test our implementation lets write a main class which will use the same data as shown in the diagram above to create a binary search tree and print its keys using all three traversal approcahes.
package ds.tree;
public class BtreeMain {
public static void main(String[] args) {
BStree bst = new BStree(5);
bst.insert(3);
bst.insert(8);
bst.insert(6);
bst.insert(4);
bst.insert(2);
bst.insert(10);
System.out.println("Inorder Traversal - ");
bst.printInOrder();
System.out.println("\nPreorder Traversal - ");
bst.printPreOrder();
System.out.println("\nPostorder Traversal - ");
bst.printPostOrder();
}
}
Output: Inorder Traversal -
2 3 4 5 6 8 10
Preorder Traversal -
5 3 2 4 8 6 10
Postorder Traversal -
2 4 3 6 10 8 5
Comments
Post a Comment