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.
Note:
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 maximum number of edges from that node to a leaf node in its subtree.
Examples:
Input: k = 25,
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,
Output: Depth of node 10 = 1 Height of node 10 = 2 Explanation: The number of edges in the path from root node to the node 10 is 1. The number of edges in the longest path connecting the node 10 to any leaf node is 2.
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) = Maximum number of edges from that node to a leaf node in its subtree.
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.
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of a Binary Tree NodestructNode{intdata;Node*left,*right;Node(intitem){data=item;left=right=nullptr;}};intfindDepth(Node*root,intx){// Base caseif(root==nullptr)return-1;intdist=-1;// Check if x is current node=if((root->data==x)// Otherwise, check if x is// present in the left subtree||(dist=findDepth(root->left,x))>=0// Otherwise, check if x is// present in the right subtree||(dist=findDepth(root->right,x))>=0)// Return depth of the nodereturndist+1;returndist;}intfindHeightUtil(Node*root,intx,int&height){if(root==nullptr){return-1;}// Store the maximum height of// the left and right subtreeintleftHeight=findHeightUtil(root->left,x,height);intrightHeight=findHeightUtil(root->right,x,height);// Update height of the current nodeintans=max(leftHeight,rightHeight)+1;// If current node is the required nodeif(root->data==x)height=ans;returnans;}intfindHeight(Node*root,intx){// Store the height of// the given nodeinth=-1;// Stores height of the TreeintmaxHeight=findHeightUtil(root,x,h);// Return the heightreturnh;}intmain(){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);intk=25;cout<<"Depth: "<<findDepth(root,k)<<"\n";cout<<"Height: "<<findHeight(root,k);return0;}
Java
// Structure of a Binary Tree NodeclassNode{intdata;Nodeleft,right;Node(intitem){data=item;left=right=null;}}publicclassGfG{intfindDepth(Noderoot,intx){// Base caseif(root==null)return-1;// Initialize distance as -1intdist=-1;// Check if x is current nodeif((root.data==x)||(dist=findDepth(root.left,x))>=0||(dist=findDepth(root.right,x))>=0)// Return depth of the nodereturndist+1;returndist;}intfindHeightUtil(Noderoot,intx,int[]height){// Base Caseif(root==null){return-1;}// Store the maximum height of the left and right subtreeintleftHeight=findHeightUtil(root.left,x,height);intrightHeight=findHeightUtil(root.right,x,height);// Update height of the current nodeintans=Math.max(leftHeight,rightHeight)+1;// If current node is the required nodeif(root.data==x)height[0]=ans;returnans;}intfindHeight(Noderoot,intx){// Store the height of the given nodeint[]h={-1};// Stores height of the TreefindHeightUtil(root,x,h);// Return the heightreturnh[0];}publicstaticvoidmain(String[]args){Noderoot=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);intk=25;GfGtree=newGfG();System.out.println("Depth: "+tree.findDepth(root,k));System.out.println("Height: "+tree.findHeight(root,k));}}
Python
classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to find depth of a given nodedeffind_depth(root,x):ifrootisNone:return-1dist=-1# Check if x is the current node or# if it exists in the left or right subtreeif(root.data==xor(dist:=find_depth(root.left,x))>=0or(dist:=find_depth(root.right,x))>=0):returndist+1returndist# Utility function to find height of a given nodedeffind_height_util(root,x,height):ifrootisNone:return-1# Store the maximum height of left and right subtreeleft_height=find_height_util(root.left,x,height)right_height=find_height_util(root.right,x,height)# Update height of the current nodeans=max(left_height,right_height)+1# If current node is the required node, update heightifroot.data==x:height[0]=ansreturnans# Function to find height of a given nodedeffind_height(root,x):height=[-1]# Using a list to # store height by referencefind_height_util(root,x,height)returnheight[0]if__name__=="__main__":# Construct the treeroot=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 and height of the given nodeprint("Depth:",find_depth(root,k))print("Height:",find_height(root,k))
C#
usingSystem;usingSystem.Collections.Generic;// Structure of a Binary Tree NodeclassNode{publicintdata;publicNodeleft,right;publicNode(intitem){data=item;left=right=null;}}classGfG{intFindDepth(Noderoot,intx){// Base caseif(root==null)return-1;// Initialize distance as -1intdist=-1;// Check if x is current nodeif((root.data==x)||(dist=FindDepth(root.left,x))>=0||(dist=FindDepth(root.right,x))>=0)// Return depth of the nodereturndist+1;returndist;}intFindHeightUtil(Noderoot,intx,refintheight){// Base Caseif(root==null){return-1;}// Store the maximum height of the left and right subtreeintleftHeight=FindHeightUtil(root.left,x,refheight);intrightHeight=FindHeightUtil(root.right,x,refheight);// Update height of the current nodeintans=Math.Max(leftHeight,rightHeight)+1;// If current node is the required nodeif(root.data==x)height=ans;returnans;}intFindHeight(Noderoot,intx){// Store the height of the given nodeinth=-1;// Stores height of the TreeFindHeightUtil(root,x,refh);// Return the heightreturnh;}publicstaticvoidMain(string[]args){Noderoot=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);intk=25;GfGtree=newGfG();Console.WriteLine("Depth: "+tree.FindDepth(root,k));Console.WriteLine("Height: "+tree.FindHeight(root,k));}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to find depth of a given nodefunctionfindDepth(root,x){if(!root)return-1;letdist=-1;// Check if x is the current node or// if it exists in the left or right subtreeif(root.data===x||(dist=findDepth(root.left,x))>=0||(dist=findDepth(root.right,x))>=0){returndist+1;}returndist;}// Utility function to find height of a given nodefunctionfindHeightUtil(root,x,height){if(!root)return-1;// Store the maximum height of left and right subtreeletleftHeight=findHeightUtil(root.left,x,height);letrightHeight=findHeightUtil(root.right,x,height);// Update height of the current nodeletans=Math.max(leftHeight,rightHeight)+1;// If current node is the required node, update heightif(root.data===x)height.value=ans;returnans;}// Function to find height of a given nodefunctionfindHeight(root,x){letheight={value:-1};// Using an object // to store height by referencefindHeightUtil(root,x,height);returnheight.value;}// Construct the treeletroot=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);letk=25;// Print depth and height of the given nodeconsole.log("Depth:",findDepth(root,k));console.log("Height:",findHeight(root,k));
Output
Depth: 2
Height: 1
Time Complexity: O(n) Auxiliary Space: O(1)
[Approach 2] Using Level Order Traversal - O(n) time and O(n) space
We can calculate the depth of each node using level order traversal by storing the current level as its depth. To calculate the height of a node k, we find the maximum depth of any leaf node in its subtree. Then: Height of node k = (Max depth of leaf in subtree) − (Depth of node k) − 1
Algorithm:
Initialize height and depth variable with -1;
Initialize a queue and a level variable with 0 and push the root in the queue.
When the value of frontNode is equal to the target k, we stop processing the nodes at that level and clear the queue to only focus on the children of the node k. This ensures that we find the furthest leaf node in the subtree of k.
So the value of depth will be equal to current level.
After completion we can calculate the value of height using height = level - depth - 1;
Print the value of height and depth variable.
C++
#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*left;Node*right;Node(intitem){data=item;left=right=nullptr;}};voidfindDepthAndHeight(Node*root,intk){if(root==nullptr)return;intdepth=-1;intheight=-1;queue<Node*>q;q.push(root);intlevel=0;while(!q.empty()){intn=q.size();for(inti=0;i<n;i++){Node*frontNode=q.front();q.pop();if(frontNode->data==k){depth=level;// Clear the queue after finding the nodewhile(!q.empty()){q.pop();}}// Push left and right children of // the current node to the queueif(frontNode->left)q.push(frontNode->left);if(frontNode->right)q.push(frontNode->right);if(frontNode->data==k){break;}}// Increment the level after processing// all nodes at the current levellevel++;}height=level-depth-1;cout<<"Depth : "<<depth<<endl;cout<<"Height : "<<height<<endl;}intmain(){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);intk=10;findDepthAndHeight(root,k);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intitem){data=item;left=right=null;}}publicclassGfG{staticvoidfindDepthAndHeight(Noderoot,intk){if(root==null)return;intdepth=-1;intheight=-1;Queue<Node>q=newLinkedList<>();q.add(root);intlevel=0;while(!q.isEmpty()){intn=q.size();for(inti=0;i<n;i++){NodefrontNode=q.poll();if(frontNode.data==k){depth=level;// Clear the queue after finding the nodeq.clear();}// Push left and right children of the current node to the queueif(frontNode.left!=null)q.add(frontNode.left);if(frontNode.right!=null)q.add(frontNode.right);if(frontNode.data==k){break;}}// Increment the level after processing all nodes at the current levellevel++;}height=level-depth-1;System.out.println("Depth : "+depth);System.out.println("Height : "+height);}publicstaticvoidmain(String[]args){Noderoot=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);intk=10;findDepthAndHeight(root,k);}}
Python
classNode:def__init__(self,item):self.data=itemself.left=Noneself.right=Nonedeffind_depth_and_height(root,k):ifrootisNone:returndepth=-1height=-1q=[root]level=0whileq:n=len(q)foriinrange(n):front_node=q.pop(0)iffront_node.data==k:depth=level# Clear the queue after finding the nodeq.clear()# Push left and right children of the current node to the queueiffront_node.left:q.append(front_node.left)iffront_node.right:q.append(front_node.right)iffront_node.data==k:break# Increment the level after processing all nodes at the current levellevel+=1height=level-depth-1print(f'Depth : {depth}')print(f'Height : {height}')defmain():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=10find_depth_and_height(root,k)if__name__=='__main__':main()
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intitem){data=item;left=right=null;}}classGfG{staticvoidFindDepthAndHeight(Noderoot,intk){if(root==null)return;intdepth=-1;intheight=-1;Queue<Node>q=newQueue<Node>();q.Enqueue(root);intlevel=0;while(q.Count>0){intn=q.Count;for(inti=0;i<n;i++){NodefrontNode=q.Dequeue();if(frontNode.data==k){depth=level;// Clear the queue after finding the nodeq.Clear();}// Push left and right children of the current node to the queueif(frontNode.left!=null)q.Enqueue(frontNode.left);if(frontNode.right!=null)q.Enqueue(frontNode.right);if(frontNode.data==k){break;}}// Increment the level after processing all nodes at the current levellevel++;}height=level-depth-1;Console.WriteLine("Depth : "+depth);Console.WriteLine("Height : "+height);}staticvoidMain(){Noderoot=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);intk=10;FindDepthAndHeight(root,k);}}
JavaScript
// Node structureclassNode{constructor(item){this.data=item;this.left=null;this.right=null;}}functionfindDepthAndHeight(root,k){if(root===null)return;letdepth=-1;letheight=-1;letqueue=[];queue.push(root);letlevel=0;while(queue.length>0){letn=queue.length;for(leti=0;i<n;i++){letfrontNode=queue.shift();if(frontNode.data===k){depth=level;// Clear the queue after finding the nodequeue=[];}// Push left and right children of the current node to the queueif(frontNode.left)queue.push(frontNode.left);if(frontNode.right)queue.push(frontNode.right);if(frontNode.data===k){break;}}// Increment the level after processing all nodes at the current levellevel++;}height=level-depth-1;console.log("Depth : "+depth);console.log("Height : "+height);}letroot=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);letk=10;findDepthAndHeight(root,k);
Output
Depth : 2
Height : 1
Time Complexity: O(n) Auxiliary Space: O(n)due to queue data structure.