Showing posts with label size of binary tree. Show all posts
Showing posts with label size of binary tree. Show all posts

Sunday, 14 October 2018

Calculate Size of binary tree Using Recusrion

public class CalculateSizeUsingRecusrion {
    public static void main(String args[]) {
             Node rootNode = new Node("4");
             rootNode.left = new Node("2");
             rootNode.left.left = new Node("1");
             rootNode.left.right = new Node("3");
             rootNode.right = new Node("6");
             rootNode.right.right = new Node("7");
             rootNode.right.left = new Node("5");
           
             System.out.println(calcSize(rootNode));
    }
   
    static int calcSize(Node node) {
        if(node==null) {
            return 0;
        }
        return calcSize(node.left)+1+calcSize(node.right);
    }
}

class BinayTree{
    static class Node{
        String value;
        Node left;
        Node right;
       
        Node(String val){
            value = val;
            left = right = null;
        }
       
    }
   
}

output: 7

Calculate Size of binary tree Using Without Recusrion

public class CalculateSizeUsingWithoutRecusrion {
    public static void main(String args[]) {
             Node rootNode = new Node("4");
             rootNode.left = new Node("2");
             rootNode.left.left = new Node("1");
             rootNode.left.left.left = new Node("9");
             rootNode.left.right = new Node("3");
             rootNode.right = new Node("6");
             rootNode.right.right = new Node("7");
             rootNode.right.left = new Node("5");
             rootNode.right.right.right = new Node("8");
           
             System.out.println(calcSize(rootNode));
    }
   
    static int calcSize(Node node) {
        Queue<Node> queue = new LinkedBlockingQueue<>();
        queue.add(node);
        int count = 0;
        while(!queue.isEmpty()) {
            Node node1 = queue.remove();
            count= count+1;
            if(null!=node1.left) {
                queue.add(node1.left);
            }
            if(null!=node1.right) {
                queue.add(node1.right);
            }
        }
        return count;
    }
}



class BinayTree{
    static class Node{
        String value;
        Node left;
        Node right;
       
        Node(String val){
            value = val;
            left = right = null;
        }
       
    }
   
}


output:9

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...