search
HomeBackend DevelopmentC++Iterative method to find height of binary tree

Iterative method to find height of binary tree

Sep 06, 2023 am 09:05 AM
Binary treeIteratehigh

Iterative method to find height of binary tree

Binary tree is a data structure. Each node of a binary tree contains 0, 1, or 2 nodes. Therefore, a binary tree can contain multiple levels.

Here, we need to write iteration code using a loop to find the height of the binary tree. The total number of levels of a binary tree represents the height of the binary tree. Alternatively, we can say that the maximum depth of a binary tree from the root node is the height of the binary tree.

Problem Statement - We are given a binary tree. We need to use an iterative method to find the height of a given binary tree.

method 1

As we said above, the height of a binary tree is equal to the total number of levels of the binary tree. We will use a queue data structure to iterate through each node of each level and find the maximum depth of the tree.

algorithm

Step 1 - Define the "treeNode" class and add the "val" integer variable. Also, define "left" and "right" pointers in the class.

Step 2- Define the createNode() function to create a new node for the tree. It creates a new treeNode, initializes "val" with the parameter value, and initializes the left and right pointers with null values. Finally return the newly created node.

Step 3 - The findHeight() function is used to find the height of the binary tree.

Step 4 - Define the "levelqueue" queue to store all nodes of the current level, the "treeHeight", "n_cnt" variables and the "temp" node.

Step 5− If the head node is Null, return 0.

Step 6- Push the head node to the "levelQueue".

Step 7- Use a "while" loop to iterate until the "levelQueue" becomes empty.

Step 8- Increase "treeHeight" by 1 and initialize "n_cnt" with the size of the queue, representing the total number of nodes at the current level.

Step 9- Iterate through all elements of the queue.

Step 9.1 - Pop the first element of the queue.

Step 9.2 − If the current node has a left child node, insert it into the queue.

Step 9.3 − If the current node has a right child node, insert it into the queue.

Step 9.4 - Remove the first node from the queue.

Step 10- Return the value of the "treeHeight" variable.

Example

#include <iostream>
#include <queue>

using namespace std;
class treeNode {
public:
    int val;
    treeNode *left;
    treeNode *right;
};
treeNode *createNode(int val) {
    //Create a new node
    treeNode *temp = new treeNode();
    temp->val = val;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
int fidHeight(treeNode *head) {
    queue<treeNode *> levelQueue;
    int treeHeight = 0; // To store the tree height of the current binary tree
    int n_cnt = 0;      // To store the total number of current level nodes.
    treeNode *temp;     // Pointer to store the address of a node in the current level.
    // For empty binary tree
    if (head == NULL) {
        return 0;
    }
    // Add root node to queue
    levelQueue.push(head);
    // Traverse level of binary tree
    while (!levelQueue.empty()) {
        // For each level increment, the treeHeight of the three
        treeHeight++;
        n_cnt = levelQueue.size();
        // Add child nodes of all nodes at the current level
        while (n_cnt--) {
            temp = levelQueue.front();
            // Insert the left child node of the current node
            if (temp->left != NULL) {
                levelQueue.push(temp->left);
            }
            // Insert the right child node of the current node
            if (temp->right != NULL) {
                levelQueue.push(temp->right);
            }
            // remove the current node
            levelQueue.pop();
        }
    }
    return treeHeight;
}
int main() {
    treeNode *head = NULL;
    // Adding nodes to binary tree.
    head = createNode(45);
    head->right = createNode(32);
    head->right->left = createNode(48);
    head->left = createNode(90);
    head->left->left = createNode(5);
    head->left->left->left = createNode(50);
    cout << "The given binary tree's treeHeight is " << fidHeight(head) << ".";
    return 0;
}

Output

The given binary tree's treeHeight is 4.

Time complexity - O(N) traversing each node.

Space Complexity - O(N) Storing nodes in the queue.

Iterative methods are always faster than recursive methods when solving any problem. Here we use loops and queues to iteratively find the maximum depth or height of a binary tree. However, a programmer might try to code a recursive method to find the height of a binary tree.

The above is the detailed content of Iterative method to find height of binary tree. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C   and Performance: Where It Still DominatesC and Performance: Where It Still DominatesMay 01, 2025 am 12:14 AM

C still dominates performance optimization because its low-level memory management and efficient execution capabilities make it indispensable in game development, financial transaction systems and embedded systems. Specifically, it is manifested as: 1) In game development, C's low-level memory management and efficient execution capabilities make it the preferred language for game engine development; 2) In financial transaction systems, C's performance advantages ensure extremely low latency and high throughput; 3) In embedded systems, C's low-level memory management and efficient execution capabilities make it very popular in resource-constrained environments.

C   XML Frameworks: Choosing the Right One for YouC XML Frameworks: Choosing the Right One for YouApr 30, 2025 am 12:01 AM

The choice of C XML framework should be based on project requirements. 1) TinyXML is suitable for resource-constrained environments, 2) pugixml is suitable for high-performance requirements, 3) Xerces-C supports complex XMLSchema verification, and performance, ease of use and licenses must be considered when choosing.

C# vs. C  : Choosing the Right Language for Your ProjectC# vs. C : Choosing the Right Language for Your ProjectApr 29, 2025 am 12:51 AM

C# is suitable for projects that require development efficiency and type safety, while C is suitable for projects that require high performance and hardware control. 1) C# provides garbage collection and LINQ, suitable for enterprise applications and Windows development. 2)C is known for its high performance and underlying control, and is widely used in gaming and system programming.

How to optimize codeHow to optimize codeApr 28, 2025 pm 10:27 PM

C code optimization can be achieved through the following strategies: 1. Manually manage memory for optimization use; 2. Write code that complies with compiler optimization rules; 3. Select appropriate algorithms and data structures; 4. Use inline functions to reduce call overhead; 5. Apply template metaprogramming to optimize at compile time; 6. Avoid unnecessary copying, use moving semantics and reference parameters; 7. Use const correctly to help compiler optimization; 8. Select appropriate data structures, such as std::vector.

How to understand the volatile keyword in C?How to understand the volatile keyword in C?Apr 28, 2025 pm 10:24 PM

The volatile keyword in C is used to inform the compiler that the value of the variable may be changed outside of code control and therefore cannot be optimized. 1) It is often used to read variables that may be modified by hardware or interrupt service programs, such as sensor state. 2) Volatile cannot guarantee multi-thread safety, and should use mutex locks or atomic operations. 3) Using volatile may cause performance slight to decrease, but ensure program correctness.

How to measure thread performance in C?How to measure thread performance in C?Apr 28, 2025 pm 10:21 PM

Measuring thread performance in C can use the timing tools, performance analysis tools, and custom timers in the standard library. 1. Use the library to measure execution time. 2. Use gprof for performance analysis. The steps include adding the -pg option during compilation, running the program to generate a gmon.out file, and generating a performance report. 3. Use Valgrind's Callgrind module to perform more detailed analysis. The steps include running the program to generate the callgrind.out file and viewing the results using kcachegrind. 4. Custom timers can flexibly measure the execution time of a specific code segment. These methods help to fully understand thread performance and optimize code.

How to use the chrono library in C?How to use the chrono library in C?Apr 28, 2025 pm 10:18 PM

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

What is real-time operating system programming in C?What is real-time operating system programming in C?Apr 28, 2025 pm 10:15 PM

C performs well in real-time operating system (RTOS) programming, providing efficient execution efficiency and precise time management. 1) C Meet the needs of RTOS through direct operation of hardware resources and efficient memory management. 2) Using object-oriented features, C can design a flexible task scheduling system. 3) C supports efficient interrupt processing, but dynamic memory allocation and exception processing must be avoided to ensure real-time. 4) Template programming and inline functions help in performance optimization. 5) In practical applications, C can be used to implement an efficient logging system.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment