binary tree implementation and traversal in java

 binary tree implementation and traversal in java

binary tree preorder,postorder,inorder java code implemenattion by bramastra trick
import java.util.Scanner;

public class binarytrees {
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
Scanner sc=new Scanner(System.in);
public Node addtree(){
Node root=null;
System.out.println("enter data");
int data=sc.nextInt();
if (data==-1){
return null;
}
root=new Node(data);
System.out.println("enter left child of root " + data);
root.left=addtree();
System.out.println("enter right child of root " + data);
root.right=addtree();
return root;
}
public void inorder(Node root){
if (root==null) return;;
inorder(root.left);
System.out.println(root.data + " ");
inorder(root.right);
}
public void preorder(Node root){
if (root==null) return;
System.out.print(root.data + " ");
preorder(root.left);
preorder(root.right);
}
public void postorder(Node soot){
if (soot==null) return;
postorder(soot.left);
postorder(soot.right);
System.out.print(soot.data + " ");

}
public static void main(String[] args) {
binarytrees bb=new binarytrees();
Node root= bb.addtree();
bb.inorder(root);
bb.preorder(root);
bb.postorder(root);

}
}

Comments

Popular posts from this blog

Back / Flip Cover Universal List

Super-D, 11D, Super X tempered glass Universal list