TREE PROGRAM
class Node{
int key;
Node left,right;
public Node(int value){
key = value;
left = right = null;
}
}
public class BinaryTree {
Node root;
BinaryTree(int value){
root = new Node(value);
}
BinaryTree() {
root = null;
}
public void printInorder(Node node){
if(node == null)
{
return ;
}
printInorder(node.left);
System.out.print(node.key+ " ");
printInorder(node.right);
}
void printInorder() {
System.out.println("Inorder Traversal");
printInorder(root);
}
void printPreOrder(Node
node){
if(node == null)
return;
System.out.print(node.key+" ");
printPreOrder(node.left);
printPreOrder(node.right);
}
void printPreOrder(){
System.out.println("Pre-order Traversal");
printPreOrder(root);
}
void printPostOrder(Node
node){
if(node == null)
return;
printPreOrder(node.left);
printPreOrder(node.right);
System.out.print(node.key+" ");
}
void printPostOrder(){
System.out.println("Pre-order Traversal");
printPostOrder(root);
}
public static void main(String []args){
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left= new Node(6);
tree.root.right.right = new Node(7);
tree.printInorder();
tree.printPreOrder();
tree.printPostOrder();
}
}
|
Inorder Traversal
4 2 5 1 6 3 7 Pre-order Traversal
1 2 4 5 3 6 7 Pre-order Traversal
2 4 5 3 6 7 1
|