Tree in java

 package Trees;

class node{
int val;
node left;
node right;
public node(int val){
    this.val=val;
}
}
public class NodeTree {
public static void main(String[] args) {
node a = new node(1);
node b = new node(4);
node c = new node(3);
node d = new node(2);
node e = new node(6);
node f = new node(5);
a.left=b; a.right=c;
b.left=d; b.right=e;
c.right=f;

System.out.print("product of all nodes : ");
System.out.print(product(a));
System.out.println();

System.out.print("product of non-zero elements of nodes : ");
System.out.print(product2(a));
System.out.println();

System.out.print("sum of all nodes : ");
System.out.print(sum(a));
System.out.println();

System.out.print("Maximum Node in tree : ");
System.out.print(maximum(a));
System.out.println();

System.out.print("Minimum Node in tree : ");
System.out.print(minimum(a));
System.out.println();

System.out.print("size of tree : ");
System.out.print(size(a));
System.out.println();

System.out.print("total levels in tree : ");
System.out.print(level(a));
System.out.println();

System.out.print("Height of tree : ");
System.out.print(level(a)-1);
System.out.println();

//three types of traversal-
System.out.print("preorder : ");
preorder(a);
System.out.println();
System.out.print("inorder : ");
inorder(a);
System.out.println();
System.out.print("postorder : ");
postorder(a);
}
public static int level(node root){
    if(root==null) return 0;
    return 1 + Math.max(level(root.left),level(root.right));
}
public static int size(node root){
    if(root==null) return 0;
    return 1 + size(root.left)+size(root.right);
}
public static int minimum(node root){
if(root==null) return Integer.MAX_VALUE;
return Math.min(root.val, Math.min(minimum(root.left),minimum(root.right)));
}
public static int maximum(node root){
if(root==null) return Integer.MIN_VALUE;
return Math.max(root.val, Math.max(maximum(root.left),maximum(root.right)));
}
public static int product2(node root){
    if(root==null) return 1;
    if(root.val==0)
    return product2(root.left) * product2(root.right);
    return root.val * product2(root.left) * product2(root.right);
}
public static int product(node root){
    if(root==null) return 1;
    return root.val * product(root.left) * product(root.right);
}
public static int sum(node root){
    if(root==null) return 0;
    return root.val + sum(root.left) + sum(root.right);
}
public static void preorder(node root){
if(root==null) return;
System.out.print(root.val+" ");
preorder(root.left);
preorder(root.right);
}
public static void inorder(node root){
if(root==null) return;
inorder(root.left);
System.out.print(root.val+" ");
inorder(root.right);
}
public static void postorder(node root){
if(root==null) return;
postorder(root.left);
postorder(root.right);
System.out.print(root.val+" ");
}
}

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.