Sunday, 9 August 2015

In-Oder traversing in Binary Tree

Information about Tree : Tree Introduction
Pre-Order Traversal in Binary Tree
Post-Order Traversal in Binary Tree

In Order Traversal in Binary Tree: First we traversal through Left child, Node and then right child. Left child should be traversed before the Parent Node traversing, Right child should be traversed after parent node.
  1. Traverse the left subtree by recursively calling the in-order function.
  2. Display the data part of root element (or current element).
  3. Traverse the right subtree by recursively calling the in-order function.
In the above Example, In Oder==> 5,9,2,6,1,8,4,3,7,10

Recursive Way:

public void inOrderRecusriveWay(BinaryDataTree<Integer> root) {
   if (root == null) {

     System.out.print(root.getData() + " ");

Iterative Way

public void inOrderIterativeWay(BinaryDataTree<Integer> root) {
        Stack<BinaryDataTree<Integer>> s = new Stack<BinaryDataTree<Integer>>();
        if (root == null) {
            System.out.println("No Element In the Tree");
        while (true) {
            while (root != null) {
                root = root.getLeft();
            if (s.isEmpty()) {

           BinaryDataTree temp = s.pop();
            System.out.print(temp.getData() + " ");

           root = temp.getRight();

No comments:

Post a comment