Height and Depth of a node in a Binary Tree
Given a Binary Tree consisting of N nodes and a integer K, the task is to find the depth and height of the node with value K in the Binary Tree.
The depth of a node is the number of edges present in path from the root node of a tree to that node.
The height of a node is the number of edges present in the longest path connecting that node to a leaf node.
Examples:
Input: K = 25,
5
/ \
10 15
/ \ / \
20 25 30 35
\
45
Output:
Depth of node 25 = 2
Height of node 25 = 1
Explanation:
The number of edges in the path from root node to the node 25 is 2. Therefore, depth of the node 25 is 2.
The number of edges in the longest path connecting the node 25 to any leaf node is 1. Therefore, height of the node 25 is 1.
Input: K = 10,
5
/ \
10 15
/ \ / \
20 25 30 35
\
45
Output:
Depth of node 10 = 1
Height of node 10 = 2
Approach: The problem can be solved based on the following observations:
Depth of a node K (of a Binary Tree) = Number of edges in the path connecting the root to the node K = Number of ancestors of K (excluding K itself).
Follow the steps below to find the depth of the given node:
- If the tree is empty, print -1.
- Otherwise, perform the following steps:
- Initialize a variable, say dist as -1.
- Check if the node K is equal to the given node.
- Otherwise, check if it is present in either of the subtrees, by recursively checking for the left and right subtrees respectively.
- If found to be true, print the value of dist + 1.
- Otherwise, print dist.
Height of a node K (of a Binary Tree) = Number of edges in the longest path connecting K to any leaf node.
Follow the steps below to find the height of the given node:
- If the tree is empty, print -1.
- Otherwise, perform the following steps:
- Calculate the height of the left subtree recursively.
- Calculate the height of the right subtree recursively.
- Update height of the current node by adding 1 to the maximum of the two heights obtained in the previous step. Store the height in a variable, say ans.
- If the current node is equal to the given node K, print the value of ans as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode( int item)
{
Node* temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
int findDepth(Node* root, int x)
{
if (root == NULL)
return -1;
int dist = -1;
if ((root->data == x)
|| (dist = findDepth(root->left, x)) >= 0
|| (dist = findDepth(root->right, x)) >= 0)
return dist + 1;
return dist;
}
int findHeightUtil(Node* root, int x,
int & height)
{
if (root == NULL) {
return -1;
}
int leftHeight = findHeightUtil(
root->left, x, height);
int rightHeight
= findHeightUtil(
root->right, x, height);
int ans = max(leftHeight, rightHeight) + 1;
if (root->data == x)
height = ans;
return ans;
}
int findHeight(Node* root, int x)
{
int h = -1;
int maxHeight = findHeightUtil(root, x, h);
return h;
}
int main()
{
Node* root = newNode(5);
root->left = newNode(10);
root->right = newNode(15);
root->left->left = newNode(20);
root->left->right = newNode(25);
root->left->right->right = newNode(45);
root->right->left = newNode(30);
root->right->right = newNode(35);
int k = 25;
cout << "Depth: "
<< findDepth(root, k) << "\n" ;
cout << "Height: " << findHeight(root, k);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int height = - 1 ;
static class Node
{
int data;
Node left;
Node right;
};
static Node newNode( int item)
{
Node temp = new Node();
temp.data = item;
temp.left = temp.right = null ;
return temp;
}
static int findDepth(Node root, int x)
{
if (root == null )
return - 1 ;
int dist = - 1 ;
if ((root.data == x)||
(dist = findDepth(root.left, x)) >= 0 ||
(dist = findDepth(root.right, x)) >= 0 )
return dist + 1 ;
return dist;
}
static int findHeightUtil(Node root, int x)
{
if (root == null )
{
return - 1 ;
}
int leftHeight = findHeightUtil(root.left, x);
int rightHeight = findHeightUtil(root.right, x);
int ans = Math.max(leftHeight, rightHeight) + 1 ;
if (root.data == x)
height = ans;
return ans;
}
static int findHeight(Node root, int x)
{
findHeightUtil(root, x);
return height;
}
public static void main(String []args)
{
Node root = newNode( 5 );
root.left = newNode( 10 );
root.right = newNode( 15 );
root.left.left = newNode( 20 );
root.left.right = newNode( 25 );
root.left.right.right = newNode( 45 );
root.right.left = newNode( 30 );
root.right.right = newNode( 35 );
int k = 25 ;
System.out.println( "Depth: " + findDepth(root, k));
System.out.println( "Height: " + findHeight(root, k));
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self .left = None
self .right = None
def findDepth(root, x):
if (root = = None ):
return - 1
dist = - 1
if (root.data = = x):
return dist + 1
dist = findDepth(root.left, x)
if dist > = 0 :
return dist + 1
dist = findDepth(root.right, x)
if dist > = 0 :
return dist + 1
return dist
def findHeightUtil(root, x):
global height
if (root = = None ):
return - 1
leftHeight = findHeightUtil(root.left, x)
rightHeight = findHeightUtil(root.right, x)
ans = max (leftHeight, rightHeight) + 1
if (root.data = = x):
height = ans
return ans
def findHeight(root, x):
global height
maxHeight = findHeightUtil(root, x)
return height
if __name__ = = '__main__' :
height = - 1
root = Node( 5 )
root.left = Node( 10 )
root.right = Node( 15 )
root.left.left = Node( 20 )
root.left.right = Node( 25 )
root.left.right.right = Node( 45 )
root.right.left = Node( 30 )
root.right.right = Node( 35 )
k = 25
print ( "Depth: " ,findDepth(root, k))
print ( "Height: " ,findHeight(root, k))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int height = -1;
class Node
{
public int data;
public Node left;
public Node right;
};
static Node newNode( int item)
{
Node temp = new Node();
temp.data = item;
temp.left = temp.right = null ;
return temp;
}
static int findDepth(Node root, int x)
{
if (root == null )
return -1;
int dist = -1;
if ((root.data == x)||
(dist = findDepth(root.left, x)) >= 0 ||
(dist = findDepth(root.right, x)) >= 0)
return dist + 1;
return dist;
}
static int findHeightUtil(Node root, int x)
{
if (root == null )
{
return -1;
}
int leftHeight = findHeightUtil(root.left, x);
int rightHeight = findHeightUtil(root.right, x);
int ans = Math.Max(leftHeight, rightHeight) + 1;
if (root.data == x)
height = ans;
return ans;
}
static int findHeight(Node root, int x)
{
findHeightUtil(root, x);
return height;
}
public static void Main()
{
Node root = newNode(5);
root.left = newNode(10);
root.right = newNode(15);
root.left.left = newNode(20);
root.left.right = newNode(25);
root.left.right.right = newNode(45);
root.right.left = newNode(30);
root.right.right = newNode(35);
int k = 25;
Console.WriteLine( "Depth: " + findDepth(root, k));
Console.WriteLine( "Height: " + findHeight(root, k));
}
}
|
Javascript
<script>
var height = -1;
class Node
{
constructor()
{
this .data = 0;
this .left = null ;
this .right = null ;
}
};
function newNode(item)
{
var temp = new Node();
temp.data = item;
temp.left = temp.right = null ;
return temp;
}
function findDepth(root, x)
{
if (root == null )
return -1;
var dist = -1;
if ((root.data == x)||
(dist = findDepth(root.left, x)) >= 0 ||
(dist = findDepth(root.right, x)) >= 0)
return dist + 1;
return dist;
}
function findHeightUtil(root, x)
{
if (root == null )
{
return -1;
}
var leftHeight = findHeightUtil(root.left, x);
var rightHeight = findHeightUtil(root.right, x);
var ans = Math.max(leftHeight, rightHeight) + 1;
if (root.data == x)
height = ans;
return ans;
}
function findHeight(root, x)
{
findHeightUtil(root, x);
return height;
}
var root = newNode(5);
root.left = newNode(10);
root.right = newNode(15);
root.left.left = newNode(20);
root.left.right = newNode(25);
root.left.right.right = newNode(45);
root.right.left = newNode(30);
root.right.right = newNode(35);
var k = 25;
document.write( "Depth: " + findDepth(root, k)+ "<br>" );
document.write( "Height: " + findHeight(root, k));
</script>
|
Output
Depth: 2
Height: 1
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach(Using Level Order Traversal): Simple and Easy to understand
Follow the below steps to solve the above problem:
1) Initialize height and depth variable with -1;
2) Initialize a queue and a level variable with 0 and push the root in the queue.
3) Perform level order traversal and if value of frontNode is equal to the target(K) node then value of depth will be equal to the level value and continue traversing.
4) After completion we can calculate the value of height using height = level – depth – 1;
5) Print the value of height and depth variable.
Below is the implementation of above approach:
C++
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* left;
Node* right;
Node( int item){
data = item;
left = right = NULL;
}
};
Node* newNode( int value){
return new Node(value);
}
void findDepthAndHeight(Node* root, int k){
if (root == NULL) return ;
int depth = -1;
int height = -1;
queue<Node*> q;
q.push(root);
int level = 0;
while (!q.empty()){
int n = q.size();
for ( int i = 0; i<n; i++){
Node* frontNode = q.front();
q.pop();
if (frontNode->data == k) depth = level;
if (frontNode->left) q.push(frontNode->left);
if (frontNode->right) q.push(frontNode->right);
}
level++;
}
height = level - depth - 1;
cout<< "Depth : " <<depth<<endl;
cout<< "Height : " <<height<<endl;
}
int main(){
Node* root = newNode(5);
root->left = newNode(10);
root->right = newNode(15);
root->left->left = newNode(20);
root->left->right = newNode(25);
root->left->right->right = newNode(45);
root->right->left = newNode(30);
root->right->right = newNode(35);
int k = 25;
findDepthAndHeight(root, k);
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left;
Node right;
Node( int item) {
data = item;
left = right = null ;
}
}
public class GFG {
static Node newNode( int value) {
return new Node(value);
}
static void findDepthAndHeight(Node root, int k) {
if (root == null )
return ;
int depth = - 1 ;
int height = - 1 ;
Queue<Node> q = new LinkedList<>();
q.add(root);
int level = 0 ;
while (!q.isEmpty()) {
int n = q.size();
for ( int i = 0 ; i < n; i++) {
Node frontNode = q.poll();
if (frontNode.data == k)
depth = level;
if (frontNode.left != null )
q.add(frontNode.left);
if (frontNode.right != null )
q.add(frontNode.right);
}
level++;
}
height = level - depth - 1 ;
System.out.println( "Depth : " + depth);
System.out.println( "Height : " + height);
}
public static void main(String[] args) {
Node root = newNode( 5 );
root.left = newNode( 10 );
root.right = newNode( 15 );
root.left.left = newNode( 20 );
root.left.right = newNode( 25 );
root.left.right.right = newNode( 45 );
root.right.left = newNode( 30 );
root.right.right = newNode( 35 );
int k = 25 ;
findDepthAndHeight(root, k);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def new_node(value):
return Node(value)
def find_depth_and_height(root, k):
if root is None :
return
depth = - 1
height = - 1
queue = []
queue.append(root)
level = 0
while queue:
n = len (queue)
for i in range (n):
front_node = queue.pop( 0 )
if front_node.data = = k:
depth = level
if front_node.left:
queue.append(front_node.left)
if front_node.right:
queue.append(front_node.right)
level + = 1
height = level - depth - 1
print ( "Depth:" , depth)
print ( "Height:" , height)
def main():
root = new_node( 5 )
root.left = new_node( 10 )
root.right = new_node( 15 )
root.left.left = new_node( 20 )
root.left.right = new_node( 25 )
root.left.right.right = new_node( 45 )
root.right.left = new_node( 30 )
root.right.right = new_node( 35 )
k = 25
find_depth_and_height(root, k)
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left;
public Node right;
public Node( int item) {
data = item;
left = right = null ;
}
}
public class GFG {
static Node newNode( int value) {
return new Node(value);
}
static void findDepthAndHeight(Node root, int k) {
if (root == null )
return ;
int depth = -1;
int height = -1;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
int level = 0;
while (q.Count != 0) {
int n = q.Count;
for ( int i = 0; i < n; i++) {
Node frontNode = q.Dequeue();
if (frontNode.data == k)
depth = level;
if (frontNode.left != null )
q.Enqueue(frontNode.left);
if (frontNode.right != null )
q.Enqueue(frontNode.right);
}
level++;
}
height = level - depth - 1;
Console.WriteLine( "Depth : " + depth);
Console.WriteLine( "Height : " + height);
}
public static void Main( string [] args) {
Node root = newNode(5);
root.left = newNode(10);
root.right = newNode(15);
root.left.left = newNode(20);
root.left.right = newNode(25);
root.left.right.right = newNode(45);
root.right.left = newNode(30);
root.right.right = newNode(35);
int k = 25;
findDepthAndHeight(root, k);
}
}
|
Javascript
class TreeNode {
constructor(value) {
this .data = value;
this .left = null ;
this .right = null ;
}
}
function findDepthAndHeight(root, k) {
if (root === null )
return ;
let depth = -1;
let height = -1;
const queue = [];
queue.push(root);
let level = 0;
while (queue.length > 0) {
const n = queue.length;
for (let i = 0; i < n; i++) {
const frontNode = queue.shift();
if (frontNode.data === k)
depth = level;
if (frontNode.left !== null )
queue.push(frontNode.left);
if (frontNode.right !== null )
queue.push(frontNode.right);
}
level++;
}
height = level - depth - 1;
console.log( "Depth: " + depth);
console.log( "Height: " + height);
}
const root = new TreeNode(5);
root.left = new TreeNode(10);
root.right = new TreeNode(15);
root.left.left = new TreeNode(20);
root.left.right = new TreeNode(25);
root.left.right.right = new TreeNode(45);
root.right.left = new TreeNode(30);
root.right.right = new TreeNode(35);
const k = 25;
findDepthAndHeight(root, k);
|
Output
Depth : 2
Height : 1
Time Complexity: O(N), where N is the number of nodes in a given binary tree.
Auxiliary Space: O(N) due to queue data structure.
Last Updated :
25 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...