Sunday 22 May 2016

Inorder Traversal of binary tree in Java

1. Traverse the left subtree by recursively calling the in-order function.
2. Display the data part of the root (or current node).
3. Traverse the right subtree by recursively calling the in-order function.

class Node {
      int key;
      Node left, right;

      public Node(int item) {
            key = item;
            left = right = null;
      }
}

class BinaryTree {

      /** Root of Binary Tree*/
      Node root;
      BinaryTree() {
            root = null;
      }

      /** Inorder binary tree traversal. */
      void printInorder(Node node) {
            if(node==null) {
                  return;
            }

            printInorder(node.left);

            System.out.println(node.key);

            printInorder(node.right);
      }

      /** Call InPrder traversal. */
      void printInorder() {
            printInorder(root);
      }
}

public class InorderTraversal {

      public static void main(String[] args) {
            BinaryTree bTree = new BinaryTree();
            bTree.root = new Node(1);
            bTree.root.left = new Node(2);
            bTree.root.right = new Node(3);
            bTree.root.left.left = new Node(4);
            bTree.root.left.right = new Node(5);
            bTree.root.left.left.left = new Node(6);
            bTree.root.left.left.right = new Node(7);

            System.out.println("\nInorder traversal of binary tree is ");
            bTree.printInorder();
      }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...