2018-05-07

Tree data structure Implementation


class Node {

int data;
Node left;
Node right;

Node(int data) {
this.data = data;

}
}

public class BaseTree {
public static void main(String[] args) {
Node root=new Node(1);

Node a1=new Node(2);
Node a2=new Node(3);
Node a3=new Node(4);
Node a4=new Node(5);
Node a5=new Node(6);
Node a6=new Node(7);


root.left=a1;
root.right=a2;

a1.left=a3;
a1.right=a4;

a2.left=a5;
a2.right=a6;


System.out.println(height(root)-1);
//preOrder(root);
//inOrder(root);
//postOrder(root);
//System.out.println(root.left.right.data);
//System.out.println(root.data);
//System.out.println(root.left.data);
//System.out.println(root.left.left.data);
//System.out.println(root.left.right.data);
//System.out.println(root.right.left.data);
//System.out.println(root.right.right.data);
}

public static void preOrder(Node root){
if(root==null){
return;
}
System.out.println(root.data);
preOrder(root.left);// root=root.left;root=root.left.left;
preOrder(root.right);
}
public static void inOrder(Node root){
if(root==null){
return;
}
preOrder(root.left);
System.out.println(root.data);
preOrder(root.right);
}
public static void postOrder(Node root){
if(root==null){
return;
}
preOrder(root.left);
preOrder(root.right);
System.out.println(root.data);
}


public static int height(Node root){
if(root==null){
return 0;
}
else
    {
        int lDepth = height(root.left);
        int rDepth = height(root.right);

        if (lDepth > rDepth)
            return (lDepth + 1);
         else
            return (rDepth + 1);
    }
}
}

No comments:

Post a Comment