- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Count Balanced Binary Trees of Height h in C++

We are given with the height H of a binary tree. The goal is to find the number/count of balanced Binary Trees of given height.

A **binary tree** − is a tree data structure in which each node has at most two children, which are the left child and the right child.

**Height-balanced binary tree** − is defined as a binary tree in which the depth of the two subtrees of every node differ by 1 or 0 only. That is the height of the left subtree and the right subtree at every node has a maximum difference of 1.

Following figure contains the possible height balanced binary trees for height h=3.

## Input

Height H=2

## Output

Count of Balanced Binary Trees of Height H is : 3

**Explanation** − Given figure contains possible balanced trees for height H=2

## Input

Height H=3

## Output

Count of Balanced Binary Trees of Height H is : 15

## Approach used in the below program is as follows

The integer H is used to represent the height of Binary trees.

The function countBTheight(int h) takes the height of the tree as input and returns the number of possible Balanced Binary trees with height h.

We are using the recursive approach.

If the tree has height 1, i.e it has only one node then only one tree with a single node is present and that is balanced. ( if(h==1), return 1)

Otherwise the height is the sum of left and right subtrees with height one or two less than the root. (Balanced trees have a difference between the heights as 1).

The function returns the count as result.

## Example

#include <iostream> int countBTheight(int h){ // One tree is possible with height 0 or 1 if (h == 0 || h == 1) return 1; return countBTheight(h-1) * (2 *countBTheight(h-2) + countBTheight(h-1)); } int main(){ int H = 4; std::cout << "Count of balanced binary trees of height H is: "<<countBTheight(H); }

## Output

Count of balanced binary trees of height H is: 315

- Related Questions & Answers
- Balanced binary search trees in Data Structure
- Enumeration of Binary Trees in C++
- Count the Number of Binary Search Trees present in a Binary Tree in C++
- Merge Two Binary Trees in C++
- Flip Equivalent Binary Trees in C++
- Unique Binary Search Trees in C++
- Binary Trees With Factors in C++
- Check if a given Binary Tree is height balanced like a Red-Black Tree in C++
- Balanced Binary Tree in Python
- Unique Binary Search Trees II in C++
- All Possible Full Binary Trees in C++
- Count number of trees in a forest in C++
- Height Limited Huffman Trees in Data Structure
- Height-Biased Leftist Trees in Data Structure
- Multidimensional Binary Search Trees