Let's Code Height and Count

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 293:- Let's Code Height and Count

Here's the C++ code to find the height and count (number of nodes) of a binary tree:

cppCopy code

#include <iostream> using namespace std; struct TreeNode {    int val;    TreeNode* left;    TreeNode* right;    TreeNode(int data) : val(data), left(nullptr), right(nullptr) {} }; int height(TreeNode* root) {    if (root == nullptr)        return 0;    int leftHeight = height(root->left);    int rightHeight = height(root->right);    return max(leftHeight, rightHeight) + 1; } int countNodes(TreeNode* root) {    if (root == nullptr)        return 0;    return countNodes(root->left) + countNodes(root->right) + 1; } int main() {    // Create a binary tree:    //        1    //       / \    //      2   3    //     / \    //    4   5    TreeNode* root = new TreeNode(1);    root->left = new TreeNode(2);    root->right = new TreeNode(3);    root->left->left = new TreeNode(4);    root->left->right = new TreeNode(5);    int treeHeight = height(root);    int nodeCount = countNodes(root);    cout << "Height of the Binary Tree: " << treeHeight << endl;    cout << "Number of nodes in the Binary Tree: " << nodeCount << endl;    // Remember to free the allocated memory after use to avoid memory leaks.    delete root->left->left;    delete root->left->right;    delete root->left;    delete root->right;    delete root;    return 0; }

Output:

sqlCopy code

Height of the Binary Tree: 3 Number of nodes in the Binary Tree: 5

In this code, we calculate the height of the binary tree as 3 (the longest path from the root to any leaf node) and the number of nodes as 5.

14. Trees

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support