Sunday 22 May 2016

Preorder Traversal of binary tree in Java

1. Display the data part of the root (or current node).
2. Traverse the left subtree by recursively calling the pre-order function.
3. Traverse the right subtree by recursively calling the pre-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 printPreorder(Node node) {
           if(node==null) {
                return;
           }

           System.out.print(node.key +" ");
          
           printPreorder(node.left);
           printPreorder(node.right);
     }

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

public class PreorderTraversal {

     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("Preorder traversal of binary tree is ");
           bTree.printPreorder();
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...