Tree traversals with recursion

package treeoperations;
class node
{
node left;
node right;
int data;
public node(int val)
{
data=val;
}
}
public class treeoperations
{
static void preorder(node root)
{
if(root!=null)
{System.out.println(root.data);
preorder(root.left);
preorder(root.right);
}
}
static void postorder(node root)
{
if(root!=null)
{postorder(root.left);
postorder(root.right);
System.out.println(root.data);
}

}

static void inorder(node root)
{
if(root!=null)
{inorder(root.left);
System.out.println(root.data);
inorder(root.right);

}

}

public static void main(String arg[])
{
node a=new node(1);
node b=new node(2);
node c=new node(3);
node d=new node(4);
node e=new node(5);
node f=new node(6);
node g=new node(7);

a.left=b;
a.right=c;
b.left=d;
b.right=e;
c.left=f;
c.right=g;
preorder(a);
System.out.println("Post order");
postorder(a);
System.out.println("In order");
inorder(a);

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *