Table of Contents
method 1
algorithm
Example
Output
Home Backend Development C++ Iterative method to find height of binary tree

Iterative method to find height of binary tree

Sep 06, 2023 am 09:05 AM
Binary tree Iterate high

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;
}
Copy after login

Output

The given binary tree's treeHeight is 4.
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Print left view of binary tree in C language Print left view of binary tree in C language Sep 03, 2023 pm 01:25 PM

The task is to print the left node of the given binary tree. First, the user will insert data, thus generating a binary tree, and then print the left view of the resulting tree. Each node can have at most 2 child nodes so this program must iterate over only the left pointer associated with the node if the left pointer is not null it means it will have some data or pointer associated with it otherwise it will be printed and displayed as the left child of the output. ExampleInput:10324Output:102Here, the orange node represents the left view of the binary tree. In the given graph the node with data 1 is the root node so it will be printed and instead of going to the left child it will print 0 and then it will go to 3 and print its left child which is 2 . We can use recursive method to store the level of node

AI technology accelerates iteration: large model strategy from Zhou Hongyi's perspective AI technology accelerates iteration: large model strategy from Zhou Hongyi's perspective Jun 15, 2023 pm 02:25 PM

Since this year, Zhou Hongyi, the founder of 360 Group, has been inseparable from one topic in all his public speeches, and that is artificial intelligence large models. He once called himself "the evangelist of GPT" and was full of praise for the breakthroughs achieved by ChatGPT, and he was firmly optimistic about the resulting AI technology iterations. As a star entrepreneur who is good at expressing himself, Zhou Hongyi's speeches are often full of witty remarks, so his "sermons" have also created many hot topics and indeed added fuel to the fire of large AI models. But for Zhou Hongyi, being an opinion leader is not enough. The outside world is more concerned about how 360, the company he runs, responds to this new wave of AI. In fact, within 360, Zhou Hongyi has already initiated a change for all employees. In April, he issued an internal letter requesting every employee and every employee of 360

How to change the height of br tag? How to change the height of br tag? Sep 11, 2023 pm 05:29 PM

Tags are a commonly used HTML element used to add line breaks in web content. Sometimes, however, the pre-existing height of line discontinuity may be deemed insufficient and the gaps between consecutive lines of written material need to be increased. In this discussion, we'll explore various ways to modify the height of a label, including using the CSS line-height property and adding auxiliary line wrapping elements. Whether you are a junior or an experienced web developer, this manual will give you a comprehensive understanding of how to adjust the height of labels in web design. Methods We will see two different methods to visibly change the height of the br tag. They are as follows - Use CSSline-height property to add extra line breaks Method One: Using CSSline-

Detailed explanation of binary tree structure in Java Detailed explanation of binary tree structure in Java Jun 16, 2023 am 08:58 AM

Binary trees are a common data structure in computer science and a commonly used data structure in Java programming. This article will introduce the binary tree structure in Java in detail. 1. What is a binary tree? In computer science, a binary tree is a tree structure in which each node has at most two child nodes. Among them, the left child node is smaller than the parent node, and the right child node is larger than the parent node. In Java programming, binary trees are commonly used to represent sorting, searching and improving the efficiency of data query. 2. Binary tree implementation in Java In Java, binary tree

In C language, print the right view of the binary tree In C language, print the right view of the binary tree Sep 16, 2023 pm 11:13 PM

The task is to print the right node of the given binary tree. First the user will insert data to create a binary tree and then print a right view of the resulting tree. The image above shows a binary tree created using nodes 10, 42, 93, 14, 35, 96, 57 and 88, with the nodes on the right side of the tree selected and displayed. For example, 10, 93, 57, and 88 are the rightmost nodes of the binary tree. Example Input:1042931435965788Output:10935788 Each node has two pointers, the left pointer and the right pointer. According to this question, the program only needs to traverse the right node. Therefore, the left child of the node does not need to be considered. The right view stores all nodes that are the last node in their hierarchy. Therefore, we can

How to implement binary tree traversal using Python How to implement binary tree traversal using Python Jun 09, 2023 pm 09:12 PM

As a commonly used data structure, binary trees are often used to store data, search and sort. Traversing a binary tree is one of the very common operations. As a simple and easy-to-use programming language, Python has many methods to implement binary tree traversal. This article will introduce how to use Python to implement pre-order, in-order and post-order traversal of a binary tree. Basics of Binary Trees Before learning how to traverse a binary tree, we need to understand the basic concepts of a binary tree. A binary tree consists of nodes, each node has a value and two child nodes (left child node and right child node

Adventures in Loops and Iteration: An Adventure in Python Code Adventures in Loops and Iteration: An Adventure in Python Code Feb 19, 2024 pm 08:48 PM

Loops and Iterations: Core Concepts in Programming Loops and iterations are essential concepts in programming that allow a program to repeatedly execute a set of instructions. Loops are used to explicitly specify the number of repetitions, while iterations are used to iterate over the elements in a collection or data structure. Types of Loops There are three main types of loops: 1. for loop A for loop is used to execute a block of code when you know the number of repetitions. Its syntax is as follows: for (initialization; condition; increment/decrement) {//code block to be executed repeatedly} For example, the following for loop prints the numbers 1 to 10: for(inti=1;i

See all articles