Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package binarytree;
- import java.util.Scanner;
- /**
- *
- * @author manth
- */
- class Node
- {
- Node()
- {
- }
- Node(int name,Node left,Node right)
- {
- this.name=name;
- this.left=left;
- this.right=right;
- }
- int name;
- Node left;
- Node right;
- }
- public class BinaryTree {
- /**
- * @param args the command line arguments
- */
- static Node root;
- public static void main(String[] args) {
- input_tree();
- System.out.println("Inroder Traversal ");
- inorder(root);
- System.out.println("preroder Traversal ");
- preorder(root);
- System.out.println("postroder Traversal ");
- postorder(root);
- }
- public static void input_tree()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println("Enter number of nodes ");
- int n=sc.nextInt();
- System.out.println(" Enter nodes names ");
- for(int i=0;i<n;i++)
- {
- int new_node_name=sc.nextInt();
- Node new_node=new Node(new_node_name,null,null);
- root=add(root,new_node);
- }
- }
- public static void inorder(Node node)
- {
- if(node!=null)
- {
- inorder(node.left);
- System.out.println(node.name+" ");
- inorder(node.right);
- }
- }
- public static void postorder(Node node)
- {
- if(node!=null)
- {
- inorder(node.left);
- inorder(node.right);
- System.out.print(node.name+" ");
- }
- }
- public static void preorder(Node node)
- {
- if(node!=null)
- {
- System.out.print(node.name+" ");
- inorder(node.left);
- inorder(node.right);
- }
- }
- public static Node add(Node node,Node new_node)
- {
- if(root==null)
- {
- root=new_node;
- node=root;
- //System.out.println("root "+ root.name);
- }
- else if(node==null)
- {
- node=new Node(new_node.name,null,null);
- //System.out.println("new "+ node.name);
- }
- else if(node.name<new_node.name)
- {
- node.right=add(node.right,new_node);
- // System.out.println("noderight pass "+node.name);
- }
- else
- node.left=add(node.left,new_node);
- return node;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment