Program to calculate Height and Depth of a node in a Binary Tree - GeeksforGeeks

30 Jun, 2021
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         \         45Output:Depth of node 25 = 2Height of node 25 = 1Explanation: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         \         45Output: Depth of node 10 = 1Height 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.
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.
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++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Structure of a Binary Tree Nodestruct Node {    int data;    Node *left, *right;}; // Utility function to create// a new Binary Tree NodeNode* newNode(int item){    Node* temp = new Node;    temp->data = item;    temp->left = temp->right = NULL;    return temp;} // Function to find the depth of// a given node in a Binary Treeint findDepth(Node* root, int x){    // Base case    if (root == NULL)        return -1;     // Initialize distance as -1    int dist = -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 node        return dist + 1;     return dist;} // Helper function to find the height// of a given node in the binary treeint findHeightUtil(Node* root, int x,                   int& height){    // Base Case    if (root == NULL) {        return -1;    }     // Store the maximum height of    // the left and right subtree    int leftHeight = findHeightUtil(        root->left, x, height);     int rightHeight        = findHeightUtil(            root->right, x, height);     // Update height of the current node    int ans = max(leftHeight, rightHeight) + 1;     // If current node is the required node    if (root->data == x)        height = ans;     return ans;} // Function to find the height of// a given node in a Binary Treeint findHeight(Node* root, int x){    // Store the height of    // the given node    int h = -1;     // Stores height of the Tree    int maxHeight = findHeightUtil(root, x, h);     // Return the height    return h;} // Driver Codeint main(){    // Binary Tree Formation    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;     // Function call to find the    // depth of a given node    cout << "Depth: "         << findDepth(root, k) << "\n";     // Function call to find the    // height of a given node    cout << "Height: " << findHeight(root, k);     return 0;}
// Java program for the above approachimport java.util.*;class GFG{ static int height = -1; // Structure of a Binary Tree Nodestatic class Node{    int data;    Node left;    Node right;}; // Utility function to create// a new Binary Tree Nodestatic Node newNode(int item){    Node temp = new Node();    temp.data = item;    temp.left = temp.right = null;    return temp;} // Function to find the depth of// a given node in a Binary Treestatic int findDepth(Node root, int x){         // Base case    if (root == null)        return -1;     // Initialize distance as -1    int dist = -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 node        return dist + 1;             return dist;} // Helper function to find the height// of a given node in the binary treestatic int findHeightUtil(Node root, int x){         // Base Case    if (root == null)    {        return -1;    }     // Store the maximum height of    // the left and right subtree    int leftHeight = findHeightUtil(root.left, x);     int rightHeight = findHeightUtil(root.right, x);     // Update height of the current node    int ans = Math.max(leftHeight, rightHeight) + 1;     // If current node is the required node    if (root.data == x)        height = ans;     return ans;} // Function to find the height of// a given node in a Binary Treestatic int findHeight(Node root, int x){         // Stores height of the Tree    findHeightUtil(root, x);     // Return the height    return height;} // Driver Codepublic static void main(String []args){         // Binary Tree Formation    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;     // Function call to find the    // depth of a given node    System.out.println("Depth: " + findDepth(root, k));     // Function call to find the    // height of a given node    System.out.println("Height: " + findHeight(root, k));}} // This code is contributed by SURENDRA_GANGWAR
# Python3 program for the above approach # Structure of a Binary Tree Nodeclass Node:    def __init__(self, x):        self.data = x        self.left = None        self.right = None         # Function to find the depth of# a given node in a Binary Treedef findDepth(root, x):       # Base case    if (root == None):        return -1     # Initialize distance as -1    dist = -1     # Check if x is current node=    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 # Helper function to find the height# of a given node in the binary treedef findHeightUtil(root, x):    global height     # Base Case    if (root == None):        return -1     # Store the maximum height of    # the left and right subtree    leftHeight = findHeightUtil(root.left, x)     rightHeight = findHeightUtil(root.right, x)     # Update height of the current node    ans = max(leftHeight, rightHeight) + 1     # If current node is the required node    if (root.data == x):        height = ans     return ans # Function to find the height of# a given node in a Binary Treedef findHeight(root, x):    global height     # Stores height of the Tree    maxHeight = findHeightUtil(root, x)     # Return the height    return height # Driver Codeif __name__ == '__main__':       # Binary Tree Formation    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     # Function call to find the    # depth of a given node    print("Depth: ",findDepth(root, k))     # Function call to find the    # height of a given node    print("Height: ",findHeight(root, k))     # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static int height = -1; // Structure of a Binary Tree Nodeclass Node{    public int data;    public Node left;    public Node right;}; // Utility function to create// a new Binary Tree Nodestatic Node newNode(int item){    Node temp = new Node();    temp.data = item;    temp.left = temp.right = null;    return temp;} // Function to find the depth of// a given node in a Binary Treestatic int findDepth(Node root, int x){         // Base case    if (root == null)        return -1;     // Initialize distance as -1    int dist = -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 node        return dist + 1;             return dist;} // Helper function to find the height// of a given node in the binary treestatic int findHeightUtil(Node root, int x){         // Base Case    if (root == null)    {        return -1;    }     // Store the maximum height of    // the left and right subtree    int leftHeight = findHeightUtil(root.left, x);     int rightHeight = findHeightUtil(root.right, x);     // Update height of the current node    int ans = Math.Max(leftHeight, rightHeight) + 1;     // If current node is the required node    if (root.data == x)        height = ans;     return ans;} // Function to find the height of// a given node in a Binary Treestatic int findHeight(Node root, int x){         // Stores height of the Tree    findHeightUtil(root, x);     // Return the height    return height;} // Driver Codepublic static void Main(){         // Binary Tree Formation    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;     // Function call to find the    // depth of a given node    Console.WriteLine("Depth: " + findDepth(root, k));     // Function call to find the    // height of a given node    Console.WriteLine("Height: " + findHeight(root, k));}} // This code is contributed by ipg2016107
<script> // JavaScript program for the above approach var height = -1; // Structure of a Binary Tree Nodeclass Node{    constructor()    {        this.data = 0;        this.left = null;        this.right = null;    }}; // Utility function to create// a new Binary Tree Nodefunction newNode(item){    var temp = new Node();    temp.data = item;    temp.left = temp.right = null;    return temp;} // Function to find the depth of// a given node in a Binary Treefunction findDepth(root, x){         // Base case    if (root == null)        return -1;     // Initialize distance as -1    var dist = -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 node        return dist + 1;             return dist;} // Helper function to find the height// of a given node in the binary treefunction findHeightUtil(root, x){         // Base Case    if (root == null)    {        return -1;    }     // Store the maximum height of    // the left and right subtree    var leftHeight = findHeightUtil(root.left, x);     var rightHeight = findHeightUtil(root.right, x);     // Update height of the current node    var ans = Math.max(leftHeight, rightHeight) + 1;     // If current node is the required node    if (root.data == x)        height = ans;     return ans;} // Function to find the height of// a given node in a Binary Treefunction findHeight(root, x){         // Stores height of the Tree    findHeightUtil(root, x);     // Return the height    return height;} // Driver Code// Binary Tree Formationvar 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;// Function call to find the// depth of a given nodedocument.write("Depth: " + findDepth(root, k)+"<br>");// Function call to find the// height of a given nodedocument.write("Height: " + findHeight(root, k));  </script>
Depth: 2
Height: 1
 
Time Complexity: O(N)Auxiliary Space: O(1)
 
mohit kumar 29
ipg2016107
SURENDRA_GANGWAR
noob2000
Binary Tree
Height of a Tree
Tree Traversals
Recursion
Searching
Tree
Searching
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Practice Questions for Recursion | Set 1
Sum of natural numbers using recursion
Recursively Reversing a linked list (A simple implementation)
Generating subarrays using recursion
Recursive Insertion Sort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number