Binary tree in java

0

 


In this blog we will see how to print construct a binary tree, print a binary tree using inorder,preorder and postorder traversal.




class Node
{
int data;
Node left,right;
Node(int data)
{
this.data=data;
this.left=null;
this.right=null;
}
}

class BinaryTree
{
public static void inorder(Node root)
{
if(root !=null)
{
inorder(root.left);
System.out.print(root.data+" ");
inorder(root.right);
}
}

public static void preorder(Node root)
{
if(root !=null)
{
System.out.print(root.data+" ");
preorder(root.left);
preorder(root.right);
}
}

public static void postorder(Node root)
{
if(root !=null)
{
postorder(root.left);
postorder(root.right);
System.out.print(root.data+" ");
}
}
public static void main(String args[])
{
Node root=new Node(10);
root.left=new Node(8);
root.right=new Node(15);
root.left.left=new Node(5);

System.out.println("\nInorder Traversal:- ");
inorder(root);

System.out.println("\nPreorder Traversal:- ");
preorder(root);

System.out.println("\nPostorder Traversal:- ");
postorder(root);
}
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !