
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum number of nodes in an AVL Tree with given height using C++.
Problem statement
Given the height of an AVL tree, the task is to find the minimum number of nodes the tree can have.
If height = 0 then AVL tree can have one 1 node If height = 5 then AVL tree can have minimum 20 nodes
Algorithm
In an AVL tree, we have to maintain the height balance property, i.e. a difference in the height of the left and the right subtrees cannot be more than -1, 0 or 1 for each node. Using this property, we can create below recurrence relation −
1. If height = 0 then return 1 2. If height = 1 then return 2 3. If height > 1 then return (1 + getMinAVLNodes(h – 1) + getMinAVLNodes(h – 2))
Example
#include <iostream> using namespace std; int getMinAVLNodes(int h){ if (h < 0) { return 0; } if (h == 0 || h == 1) { return h + 1; } return 1 + getMinAVLNodes(h - 1) + getMinAVLNodes(h -2); } int main(){ int h = 5; cout << "Minimum nodes for " << h << " height = " << getMinAVLNodes(h) << endl; return 0; }
Output
When you compile and execute the above program. It generates the following output −
Minimum nodes for 5 height = 20
- Related Articles
- Count the number of nodes at given level in a tree using BFS in C++
- C++ program to Check if a Given Binary Tree is an AVL Tree or Not
- AVL tree in Javascript
- AVL Tree class in Javascript
- Number of nodes greater than a given value in n-ary tree in C++
- Python Program to Count Number of Non Leaf Nodes of a given Tree
- Program to find number of nodes in the sub-tree with the same label using Python
- C++ Program to Implement AVL Tree
- Minimum height of a triangle with given base and area in C++
- Minimum number using set bits of a given number in C++
- Print all leaf nodes of an n-ary tree using DFS in C++
- Program to find minimum number of vertices to reach all nodes using Python
- Inserting a node in a Javascript AVL Tree
- Number of leaf nodes in the subtree of every node of an n-ary tree in C++
- Find height of a special binary tree whose leaf nodes are connected in C++

Advertisements