|
| 1 | +/* |
| 2 | +Given the root of a Complete Binary Tree consisting of N nodes, the task is to find the total number of nodes in the given Binary Tree. |
| 3 | +*/ |
| 4 | + |
| 5 | +// Java program for the above approach |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +class GFG{ |
| 9 | + |
| 10 | +// Structure of a Tree Node |
| 11 | +static class node { |
| 12 | + |
| 13 | + int data; |
| 14 | + node left; |
| 15 | + node right; |
| 16 | +}; |
| 17 | + |
| 18 | + |
| 19 | +// Function to get the left height of |
| 20 | +// the binary tree |
| 21 | +static int left_height(node node) |
| 22 | +{ |
| 23 | + int ht = 0; |
| 24 | + while (node!=null) { |
| 25 | + ht++; |
| 26 | + node = node.left; |
| 27 | + } |
| 28 | + |
| 29 | + // Return the left height obtained |
| 30 | + return ht; |
| 31 | +} |
| 32 | + |
| 33 | +// Function to get the right height |
| 34 | +// of the binary tree |
| 35 | +static int right_height(node node) |
| 36 | +{ |
| 37 | + int ht = 0; |
| 38 | + while (node!=null) { |
| 39 | + ht++; |
| 40 | + node = node.right; |
| 41 | + } |
| 42 | + |
| 43 | + // Return the right height obtained |
| 44 | + return ht; |
| 45 | +} |
| 46 | + |
| 47 | +// Function to get the count of nodes |
| 48 | +// in complete binary tree |
| 49 | +static int TotalNodes(node root) |
| 50 | +{ |
| 51 | + |
| 52 | + // Base Case |
| 53 | + if (root == null) |
| 54 | + return 0; |
| 55 | + |
| 56 | + // Find the left height and the |
| 57 | + // right heights |
| 58 | + int lh = left_height(root); |
| 59 | + int rh = right_height(root); |
| 60 | + |
| 61 | + // If left and right heights are |
| 62 | + // equal return 2^height(1<<height) -1 |
| 63 | + if (lh == rh) |
| 64 | + return (1 << lh) - 1; |
| 65 | + |
| 66 | + // Otherwise, recursive call |
| 67 | + return 1 + TotalNodes(root.left) |
| 68 | + + TotalNodes(root.right); |
| 69 | +} |
| 70 | + |
| 71 | +// Helper function to allocate a new node |
| 72 | +// with the given data |
| 73 | +static node newNode(int data) |
| 74 | +{ |
| 75 | + node Node = new node(); |
| 76 | + Node.data = data; |
| 77 | + Node.left = null; |
| 78 | + Node.right = null; |
| 79 | + return (Node); |
| 80 | +} |
| 81 | + |
| 82 | +// Driver Code |
| 83 | + public static void main(String[] args) |
| 84 | + { |
| 85 | + node root = newNode(1); |
| 86 | + root.left = newNode(2); |
| 87 | + root.right = newNode(3); |
| 88 | + root.left.left = newNode(4); |
| 89 | + root.left.right = newNode(5); |
| 90 | + root.right.left = newNode(9); |
| 91 | + root.right.right = newNode(8); |
| 92 | + root.left.left.left = newNode(6); |
| 93 | + root.left.left.right = newNode(7); |
| 94 | + |
| 95 | + System.out.print(TotalNodes(root)); |
| 96 | + |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +// This code is contributed by shikhasingrajput |
0 commit comments