Saturday, September 8, 2012

Basic Binary Tree Operations

package com.abhi.Tree;


class Node {
   
    int data;
    Node left;
    Node right;
}
public class createABinaryTree {

    static Node root = null;
    public static Node addNode(int data, Node root){
        if(root == null){
           
            Node t = new Node();
            t.data = data;
            //root = t;
            return t;
        }
        if(root.data > data)
                root.left = addNode(data,root.left);
        else
            root.right = addNode(data,root.right);
       
        return root;
       
    }
   
   
    public static void main(String st[]){
        Node root = addNode(6, null);
        addNode(3, root);
        addNode(10, root);
        addNode(11,root);
        addNode(12,root);

        //addNode(5,root);
        //addNode(13,root);
        //addNode(-1,root);
        System.out.println(root);
        System.out.println("Number of Nodes"+numberOfNodes(root));
        System.out.println("Max Depth"+maxDepth(root));
        inOrder(root);
        pathSum(root, 0);
       
        doubleTree(root);
        System.out.println("-----");
        inOrder(root);
    }
   
     static int numberOfNodes(Node n){
       
        if(n== null)
            return  0;
        return(1+numberOfNodes(n.left)+numberOfNodes(n.right));
       
    }
   
     static int maxDepth(Node n){
         if(n == null)
             return 0;
         int leftLen = maxDepth(n.left);
         int rightLen = maxDepth(n.right);
       
         if(leftLen > rightLen){
             return leftLen+1;
         }else
             return rightLen+1;
     }
   
 static void  inOrder(Node n){
     if(n== null)
         return;
     inOrder(n.left);
     System.out.print(n.data+" ");
     inOrder(n.right);
 }
 static void pathSum(Node n , int sum){
   
   
     if(n== null)
         return;
     if(n.left == null && n.right == null ){
         System.out.println(sum+n.data);
         return;
     }
    // if(n.left!=null)
         pathSum(n.left, sum+n.data);
     //if(n.right!=null)
     pathSum(n.right, sum+n.data);
 }

 static void doubleTree(Node n){
   
     if(n == null )
         return;
   
   
     doubleTree(n.left);
     Node temp = new Node();
     temp.data = n.data;
     Node tt = n.left;
     temp.left = tt;
     n.left = temp;
   
   
 }


}

No comments:

Post a Comment