Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Comparison between Height Balanced Tree and Weight Balanced Tree
Next article icon

Count Balanced Binary Trees of Height h

Last Updated : 10 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a height h, count and return the maximum number of balanced binary trees possible with height h. A balanced binary tree is one in which for every node, the difference between heights of left and right subtree is not more than 1.

Examples : 

Input : h = 3 Output : 15  Input : h = 4 Output : 315
Recommended Practice
BBT counter
Try It!

Following are the balanced binary trees of height 3. 
 

Height of tree, h = 1 + max(left height, right height)
Since the difference between the heights of left and right subtree is not more than one, possible heights of left and right part can be one of the following: 
 

  1. (h-1), (h-2)
  2. (h-2), (h-1)
  3. (h-1), (h-1)
count(h) = count(h-1) * count(h-2) +             count(h-2) * count(h-1) +             count(h-1) * count(h-1)         = 2 * count(h-1) * count(h-2) +             count(h-1) * count(h-1)        = count(h-1) * (2*count(h - 2) +                            count(h - 1))

Hence we can see that the problem has optimal substructure property.

A recursive function to count no of balanced binary trees of height h is: 

int countBT(int h) {     // One tree is possible with height 0 or 1     if (h == 0 || h == 1)         return 1;     return countBT(h-1) * (2 *countBT(h-2) +                               countBT(h-1)); }

The time complexity of this recursive approach will be exponential. The recursion tree for the problem with h = 3 looks like : 
 


As we can see, sub-problems are solved repeatedly. Therefore we store the results as we compute them. 

An efficient dynamic programming approach will be as follows : 

Below is the implementation of above approach:

C++
// C++ program to count number of balanced // binary trees of height h. #include <bits/stdc++.h> #define mod 1000000007 using namespace std;   long long int countBT(int h) {           long long int dp[h + 1];     //base cases     dp[0] = dp[1] = 1;     for(int i = 2; i <= h; i++) {         dp[i] = (dp[i - 1] * ((2 * dp [i - 2])%mod + dp[i - 1])%mod) % mod;     }     return dp[h]; }   // Driver program int main() {     int h = 3;     cout << "No. of balanced binary trees"             " of height h is: "          << countBT(h) << endl; } 
Java
// Java program to count number of balanced  // binary trees of height h.  import java.io.*; class GFG {          static final int MOD = 1000000007;          public static long countBT(int h) {         long[] dp = new long[h + 1];                  // base cases         dp[0] = 1;         dp[1] = 1;                  for(int i = 2; i <= h; ++i)              dp[i] = (dp[i - 1] * ((2 * dp [i - 2])% MOD + dp[i - 1]) % MOD) % MOD;                          return dp[h];     }          // Driver program     public static void main (String[] args) {         int h = 3;          System.out.println("No. of balanced binary trees of height "+h+" is: "+countBT(h));      } } /* This code is contributed by Brij Raj Kishore */ 
Python3
# Python3 program to count number of balanced  # binary trees of height h.   def countBT(h) :     MOD = 1000000007     #initialize list     dp = [0 for i in range(h + 1)]          #base cases     dp[0] = 1     dp[1] = 1          for i in range(2, h + 1) :         dp[i] = (dp[i - 1] * ((2 * dp [i - 2])%MOD + dp[i - 1])%MOD) % MOD          return dp[h]  #Driver program h = 3 print("No. of balanced binary trees of height "+str(h)+" is: "+str(countBT(h)))  # This code is contributed by # Brij Raj Kishore 
C#
// C# program to count number of balanced  // binary trees of height h.   using System; class GFG {           static int MOD = 1000000007;           public static long countBT(int h) {          long[] dp = new long[h + 1];                   // base cases          dp[0] = 1;          dp[1] = 1;                   for(int i = 2; i <= h; ++i)              dp[i] = (dp[i - 1] * ((2 * dp [i - 2])% MOD + dp[i - 1]) % MOD) % MOD;                           return dp[h];      }           // Driver program      static void Main () {          int h = 3;          Console.WriteLine("No. of balanced binary trees of height "+h+" is: "+countBT(h));      }      // This code is contributed by Ryuga }  
PHP
<?php // PHP program to count // number of balanced  $mod =1000000007;  function countBT($h) {     global $mod;          // base cases     $dp[0] = $dp[1] = 1;     for($i = 2; $i <= $h; $i++)      {         $dp[$i] = ($dp[$i - 1] *                    ((2 * $dp [$i - 2]) %                    $mod + $dp[$i - 1]) %                            $mod) % $mod;     }     return $dp[$h]; }   // Driver Code $h = 3; echo "No. of balanced binary trees",                 " of height h is: ",                     countBT($h) ,"\n";   // This code is contributed by aj_36 ?> 
JavaScript
<script>     // Javascript program to count number of balanced binary trees of height h.          let MOD = 1000000007;             function countBT(h) {          let dp = new Array(h + 1);          dp.fill(0);                    // base cases          dp[0] = 1;          dp[1] = 1;                     for(let i = 2; i <= h; ++i)              dp[i] = (dp[i - 1] * ((2 * dp [i - 2])% MOD + dp[i - 1]) % MOD) % MOD;                             return dp[h];      }          let h = 3;        document.write("No. of balanced binary trees of height h is: "+countBT(h));       </script> 

Output
No. of balanced binary trees of height h is: 15

Time Complexity: O(n)
Auxiliary Space: O(n), since n extra space has been taken.

Memory efficient Dynamic Programming approach : 

If we observe carefully, in the previous approach to calculate dp[i] we are using dp[i-1] and dp[i-2] only and dp[0] to dp[i-3] are no longer required. Hence we can replace dp[i],dp[i-1] and dp[i-2] with dp2, dp1 and dp0 respectively. ( contributed by Kadapalla Nithin Kumar)

Implementation:

C++
// C++ program to count number of balanced // binary trees of height h. #include <bits/stdc++.h> using namespace std;   long long int countBT(int h) {       if(h<2){       return 1;     }       const int BIG_PRIME = 1000000007;     long long int dp0 = 1, dp1 = 1,dp2;        for(int i = 2; i <= h; i++) {            dp2 = (dp1 * ((2 * dp0)%BIG_PRIME + dp1)%BIG_PRIME) % BIG_PRIME;                  // update dp1 and dp0         dp0 = dp1;           dp1 = dp2;            // Don't commit following simple mistake            // dp1 = dp0;         // dp0 = dp1;     }     return dp2; }   // Driver program int main() {     int h = 3;     cout << "No. of balanced binary trees"             " of height h is: "          << countBT(h) << endl; } // This code is contributed by Kadapalla Nithin Kumar 
Java
// Java program to count number of balanced  // binary trees of height h.  import java.io.*; class GFG {          static final int BIG_PRIME = 1000000007;     static long countBT(int h){         if(h<2){           return 1;         }         long dp0 = 1, dp1 = 1,dp2 = 3;                for(int i = 2; i <= h; i++) {                    dp2 = (dp1 * ((2 * dp0)%BIG_PRIME + dp1)%BIG_PRIME) % BIG_PRIME;                          // update dp1 and dp0             dp0 = dp1;               dp1 = dp2;                    // Don't commit following simple mistake                // dp1 = dp0;             // dp0 = dp1;         }         return dp2;     }     // Driver program     public static void main (String[] args) {         int h = 3;          System.out.println("No. of balanced binary trees of height "+h+" is: "+countBT(h));      } } /* This code is contributed by Brij Raj Kishore and modified by Kadapalla Nithin Kumar */ 
Python3
# Python3 program to count number of balanced  # binary trees of height h.   def countBT(h) :     BIG_PRIME = 1000000007     if h < 2:           return 1     dp0 = dp1 = 1     dp2 = 3     for _ in range(2,h+1):         dp2 = (dp1*dp1 + 2*dp1*dp0)%BIG_PRIME         dp0 = dp1         dp1 = dp2     return dp2 #Driver program h = 3 print("No. of balanced binary trees of height "+str(h)+" is: "+str(countBT(h)))  #This code is contributed by Kadapalla Nithin Kumar 
C#
// C# program to count number of balanced  // binary trees of height h.   using System; class GFG {           static int BIG_PRIME = 1000000007;           public static long countBT(int h) {           // base case           if(h<2){           return 1;         }            long dp0 = 1;          long dp1 = 1;          long dp2 = 3;         for(int i = 2; i <= h; ++i){              dp2 = (dp1 * ((2 * dp0)% BIG_PRIME + dp1) % BIG_PRIME) % BIG_PRIME;               dp0 = dp1;               dp1 = dp2;         }        return dp2;      }           // Driver program      static void Main () {          int h = 3;          Console.WriteLine("No. of balanced binary trees of height "+h+" is: "+countBT(h));      }      // This code is contributed by Ryuga and modified by Kadapalla Nithin Kumar }  
PHP
<?php // PHP program to count // number of balanced  $BIG_PRIME =1000000007;  function countBT($h) {     global $BIG_PRIME;          // base cases       if($h < 2){       return 1;     }     $dp0 = $dp1 = 1;     $dp2 = 3;     for($i = 2; $i <= $h; $i++)      {         $dp2 = ($dp1 *                    ((2 * $dp0) % $BIG_PRIME                   + $dp1) %                            $BIG_PRIME) % $BIG_PRIME;           $dp0 = $dp1;           $dp1 = $dp2;     }     return $dp2; }   // Driver Code $h = 3; echo "No. of balanced binary trees",                 " of height h is: ",                     countBT($h) ,"\n";   // This code is contributed by aj_36 and modified by Kadapalla Nithin Kumar ?> 
JavaScript
<script>     // Javascript program to count number of balanced binary trees of height h.          let BIG_PRIME = 1000000007;             function countBT(h) {          if(h<2){             return 1;         }         // base cases          let dp0 = 1;          let dp1 = 1;          let dp2 = 3;         for(let i = 2; i <= h; ++i){              dp2 = (dp1 * ((2 * dp0)% MOD + dp1) % MOD) % MOD;             dp0 = dp1;             dp1 = dp2;         }         return dp2;     }          let h = 3;        document.write("No. of balanced binary trees of height h is: "+countBT(h));      // This code is contributed by Kadapalla Nithin Kumar </script> 

Output
No. of balanced binary trees of height h is: 15

Time Complexity: O(n)
Auxiliary Space: O(1)

other Geek. 


Next Article
Comparison between Height Balanced Tree and Weight Balanced Tree

A

Aditi Sharma
Improve
Article Tags :
  • Tree
  • Dynamic Programming
  • Mathematical
  • DSA
Practice Tags :
  • Dynamic Programming
  • Mathematical
  • Tree

Similar Reads

  • Introduction to Tree Data Structure
    Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree. Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) o
    15+ min read
  • Tree Traversal Techniques
    Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss all the tree travers
    7 min read
  • Applications of tree data structure
    A tree is a type of data structure that represents a hierarchical relationship between data elements, called nodes. The top node in the tree is called the root, and the elements below the root are called child nodes. Each child node may have one or more child nodes of its own, forming a branching st
    4 min read
  • Advantages and Disadvantages of Tree
    Tree is a non-linear data structure. It consists of nodes and edges. A tree represents data in a hierarchical organization. It is a special type of connected graph without any cycle or circuit. Advantages of Tree:Efficient searching: Trees are particularly efficient for searching and retrieving data
    2 min read
  • Difference between an array and a tree
    Array:An array is a collection of homogeneous(same type) data items stored in contiguous memory locations. For example, if an array is of type “int”, it can only store integer elements and cannot allow the elements of other types such as double, float, char, etc. The array is a linear data structure
    3 min read
  • Inorder Tree Traversal without Recursion
    Given a binary tree, the task is to perform in-order traversal of the tree without using recursion. Example: Input: Output: 4 2 5 1 3Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3 Input: Output: 1 7 10 8 6 10 5 6Explanation: Inorder traversal (Left->Root->Rig
    8 min read
  • Types of Trees in Data Structures
    A tree in data structures is a hierarchical data structure that consists of nodes connected by edges. It is used to represent relationships between elements, where each node holds data and is connected to other nodes in a parent-child relationship. Types of Trees The main types of trees in data stru
    4 min read
  • Generic Trees (N-ary Tree)

    • Introduction to Generic Trees (N-ary Trees)
      Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and t
      5 min read

    • Inorder traversal of an N-ary Tree
      Given an N-ary tree containing, the task is to print the inorder traversal of the tree. Examples:  Input: N = 3   Output: 5 6 2 7 3 1 4Input: N = 3   Output: 2 3 5 1 4 6  Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finall
      6 min read

    • Preorder Traversal of an N-ary Tree
      Given an N-ary Tree. The task is to write a program to perform the preorder traversal of the given n-ary tree. Examples: Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 Output: 1 2 5 10 6 11 12 13 3 4 7 8 9 Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 O
      14 min read

    • Iterative Postorder Traversal of N-ary Tree
      Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We wi
      10 min read

    • Level Order Traversal of N-ary Tree
      Given an N-ary Tree. The task is to print the level order traversal of the tree where each level will be in a new line. Examples: Input: Output: 13 2 45 6Explanation: At level 1: only 1 is present.At level 2: 3, 2, 4 is presentAt level 3: 5, 6 is present Input: Output: 12 3 4 56 7 8 9 1011 12 1314Ex
      11 min read

    • ZigZag Level Order Traversal of an N-ary Tree
      Given a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow
      8 min read

    Binary Tree

    • Introduction to Binary Tree
      Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Representation of Binary TreeEach node in a Binar
      15+ min read

    • Properties of Binary Tree
      This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levels Note: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A binary tree can have at most
      4 min read

    • Applications, Advantages and Disadvantages of Binary Tree
      A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
      2 min read

    • Binary Tree (Array implementation)
      Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
      6 min read

    • Complete Binary Tree
      We know a tree is a non-linear data structure. It has no limitation on the number of children. A binary tree has a limitation as any node of the tree has at most two children: a left and a right child. What is a Complete Binary Tree?A complete binary tree is a special type of binary tree where all t
      7 min read

    • Perfect Binary Tree
      What is a Perfect Binary Tree? A perfect binary tree is a special type of binary tree in which all the leaf nodes are at the same depth, and all non-leaf nodes have two children. In simple terms, this means that all leaf nodes are at the maximum depth of the tree, and the tree is completely filled w
      4 min read

    Ternary Tree

    • Create a Doubly Linked List from a Ternary Tree
      Given a ternary tree, create a doubly linked list out of it. A ternary tree is just like a binary tree but instead of having two nodes, it has three nodes i.e. left, middle, and right. The doubly linked list should hold the following properties – The left pointer of the ternary tree should act as pr
      12 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences