Find The Maximum Depth or Height of Given Binary

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Array Matrix Strings Hashing Linked List Stack

Find the Maximum


Depth or Height of
given Binary Tree
Difficulty Level : Easy
Last Updated : 03 Oct, 2022

Given a binary tree, the task is to find the


height of the tree. Height of the tree is the
number of edges in the tree from the root to
the deepest node, Height of the empty tree is
0.
 

Sponsored

Olymptrade

Trade with precision

Install now

Recommended Problem

Height of Binary Tree Solve


Problem
Tree

Amazon Cadence India +12 more Submission


count: 1.8L

Find Maximum Depth or Height


of Tree using Depth First
Traversal:

Recursively calculate height of left and


right subtrees of a node and assign
height to the node as max of the heights
of two children plus 1. See below
pseudo code and program for details.

Illustration:

Consider the following graph:

maxDepth(‘1’) = max(maxDepth(‘2’),
maxDepth(‘3’)) + 1 = 2 + 1

because recursively 
maxDepth(‘2’) =  max (maxDepth(‘4’),
maxDepth(‘5’)) + 1 = 1 + 1 and  (as
height of both ‘4’ and ‘5’ are 1)
maxDepth(‘3’) = 1

Follow the below steps to Implement the idea:

Recursively do a Depth-first search.


If the tree is empty then return -1
Otherwise, do the following
Get the max depth of the left subtree
recursively  i.e. call maxDepth( tree-
>left-subtree)
Get the max depth of the right subtree
recursively  i.e. call maxDepth( tree-
>right-subtree)
Get the max of max depths of left and
right subtrees and add 1 to it for the
current node.

Return max_depth.

Below is the Implementation of the above


approach:

C++

#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to


and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};

/* Compute the "maxDepth" of a tree -- the


nodes along the longest path from the
down to the farthest leaf node.*/
int maxDepth(struct node* node)
{
if (node == NULL)
return 0;
else {
/* compute the depth of each subtr
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right)

/* use the larger one */


if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}

/* Helper function that allocates a new no


given data and NULL left and right poin
struct node* newNode(int data)
{
struct node* node
= (struct node*)malloc(sizeof(
node->data = data;
node->left = NULL;
node->right = NULL;

return (node);
}

int main()
{
struct node* root = newNode(1);

root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("Height of tree is %d", maxDept

getchar();
return 0;
}

Java

Python3

C#

Javascript

Output

Height of tree is 3

Time Complexity: O(N) (Please see our post


Tree Traversal for details)
Auxiliary Space: O(N) due to recursive stack.

Find the Maximum Depth or


Height of a Tree using Level
Order Traversal:

Do Level Order Traversal, while adding


Nodes at each level to Queue, we have
to add NULL Node so that whenever it is
encountered, we can increment the
value of variable and that level get
counted.

Follow the below steps to Implement the idea:

Traverse the tree in level order traversal


starting from root.
Initialize an empty queue Q, a variable
depth and push root, then push null into
the Q.
Run a while loop till Q is not empty.
Store the front element of Q and Pop
out the front element.
If the front of Q is NULL then
increment depth by one and if queue
is not empty then push NULL into the
Q.
Else if the element is not NULL then
check for its left and right children
and if they are not NULL push them
into Q.
Return depth.

Below is the Implementation of the above


approach:

C++

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

// A Tree node
struct Node {
int key;
struct Node *left, *right;
};

// Utility function to create a new node


Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}

/*Function to find the height(depth) of th


int height(struct Node* root)
{

// Initialising a variable to count th


// height of tree
int depth = 0;

queue<Node*> q;

// Pushing first level element along w


q.push(root);
q.push(NULL);
while (!q.empty()) {
Node* temp = q.front();
q.pop();

// When NULL encountered, incremen


if (temp == NULL) {
depth++;
}

// If NULL not encountered, keep m


if (temp != NULL) {
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}

// If queue still have elements le


// push NULL again to the queue.
else if (!q.empty()) {
q.push(NULL);
}
}
return depth;
}

// Driver program
int main()
{
// Let us create Binary Tree shown in
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);

root->left->left = newNode(4);
root->left->right = newNode(5);

cout << "Height(Depth) of tree is: "


}

Java

Python3

Javascript

Output

Height(Depth) of tree is: 3

Time Complexity: O(N)


Auxiliary Space: O(N)

Another method to find height using


Level Order Traversal:

This method also uses the concept of


Level Order Traversal but we wont be
adding null in the Queue. Simply
increase the counter when the level
increases and push the children of
current node into the queue, then
remove all the nodes from the queue of
the current Level.

C++

// C++ program for above approach


#include <bits/stdc++.h>
using namespace std;

// A Tree node
struct Node {
int key;
struct Node *left, *right;
};

// Utility function to create a new node


Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}

/*Function to find the height(depth) of th


int height(Node* root)
{

// Initialising a variable to count the


// height of tree
queue<Node*> q;
q.push(root);
int height = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL) {
q.push(temp->left);
}
if (temp->right != NULL) {
q.push(temp->right);
}
}
height++;
}
return height;
}

// Driver program
int main()
{

// Let us create Binary Tree shown in ab


Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);

root->left->left = newNode(4);
root->left->right = newNode(5);

cout << "Height(Depth) of tree is: "


}

// This code is contributed by Abhijeet Ku

Java

Output

Height(Depth) of tree is: 3

Time Complexity: O(N)


Auxiliary Space: O(N)

Like 202

Previous Next

R ECO M M E N D E D A RT I C L E S
Page : 1 2 3 4 5 6

01 Height and Depth of a node in a


Binary Tree
05, Mar 21

02 Sum of nodes at maximum depth of a


Binary Tree | Iterative Approach
10, Jul 18

03 Sum of nodes at maximum depth of a


Binary Tree | Set 2
24, Jan 19

04 Sum of nodes at maximum depth of a


Binary Tree
29, Mar 18

Article Contributed By :

GeeksforGeeks

Vote for difficulty


Current difficulty : Easy

Easy Normal Medium Hard

Expert

Improved By : coduitachi, rathbhupendra,


29AjayKumar, ronitnaik,
vivekans2016, rag2127,
sarthakdelori10, as3814,
jana_sayantan, shinjanpatra,
prashantsrivastava6,
polymatir3j, hardikkoriintern,
akshitsaxenaa09,
porsiyaamrita,
aashutoshparoha,
abhijeet19403

Article Tags : Amazon, Cadence India,


CouponDunia, FactSet,
FreeCharge, Height of a Tree,
MakeMyTrip,
Monotype Solutions, Snapdeal,
Synopsys, Teradata,
tree-traversal, Trees, VMWare,
Zoho, Tree

Practice Tags : Amazon, Cadence India,


CouponDunia, FactSet,
FreeCharge, MakeMyTrip,
Monotype Solutions, Snapdeal,
Synopsys, Teradata, VMWare,
Zoho, Tree

Improve Article Report Issue

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and


share the link here.

Load Comments

W H AT ' S N E W

Amazon SDE Preparation Test Series

Extra 20% Off I View Offer

View Details

Data Structures & Algorithms- Self Paced


Course

Extra 20% Off I View Offer

View Details

Complete Interview Preparation- Self


Paced Course

Extra 20% Off I View Offer

View Details

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org

Company

About Us

Careers

In Media

Contact Us

Privacy Policy

Copyright Policy

Learn

Algorithms

Data Structures

SDE Cheat Sheet

Machine learning

CS Subjects

Video Tutorials

Courses

News

Top News

Technology

Work & Career

Business

Finance

Lifestyle

Knowledge

Languages

Python

Java

CPP

Golang

C#

SQL

Kotlin

Web Development

Web Tutorials

Django Tutorial

HTML

JavaScript

Bootstrap

ReactJS

NodeJS

Contribute

Write an Article

Improve an Article

Pick Topics to Write

Write Interview Experience

Internships

Video Internship

@geeksforgeeks , Some rights reserved

You might also like