The Wayback Machine - https://web.archive.org/web/20241115072021/https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/
Open In App

Maximum Depth or Height of Binary Tree

Last Updated : 27 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary tree, the task is to find the maximum depth or height of the tree. The height of the tree is the number of vertices in the tree from the root to the deepest node.

Examples:

Example 1: The height of the below binary tree is 3.

ex-11


Example 2: The height of the below binary tree is 4

ex-4

[Expected Approach – 1] Using Recursion – O(n) Time and O(n) Space

The idea is to recursively calculate the height of the left and the right subtrees of a node and assign height to the node as max of the heights of two children plus 1.

Follow the steps below to solve the problem:

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

Below is the Implementation of the above approach:

C++
// C++ program to find the maximum depth of a binary 
// tree using depth-first search (DFS) approach.

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

struct Node {
    int data;
    Node *left;
    Node *right;

    Node(int val) {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// Returns "maxDepth" which is the number of nodes 
// along the longest path from the root node down 
// to the farthest leaf node.
int maxDepth(Node *node) {
    if (node == nullptr)
        return 0;

    // compute the depth of left and right subtrees
    int lDepth = maxDepth(node->left);
    int rDepth = maxDepth(node->right);

    return max(lDepth, rDepth) + 1;
}

int main() {
  
    // Representation of the input tree:
    //     1
    //    / \
    //   2   3
    //  / \
    // 4   5
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    
    cout << maxDepth(root);
    
    return 0;
}
C
// C program to find the maximum depth of a binary 
// tree using depth-first search (DFS) approach.
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
}; 

// Returns "maxDepth" which is the number of nodes 
// along the longest path from the root node down 
// to the farthest leaf node.
int maxDepth(struct Node* node) {
    if (node == NULL)
        return 0;

    // compute the depth of left and right subtrees
    int lDepth = maxDepth(node->left);
    int rDepth = maxDepth(node->right);

    return (lDepth > rDepth ? lDepth : rDepth) + 1;
}

struct Node* createNode(int val) {
    struct Node* node 
        = (struct Node*)malloc(sizeof(struct Node));
    node->data = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}

int main() {
  
    // Representation of the input tree:
    //     1
    //    / \
    //   2   3
    //  / \
    // 4   5
    struct Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    
    printf("%d\n", maxDepth(root));
    
    return 0;
}
Java
// Java program to find the maximum depth of a binary 
// tree using depth-first search (DFS) approach.
class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

// Returns "maxDepth" which is the number of nodes 
// along the longest path from the root node down 
// to the farthest leaf node.
class GfG {
    static int maxDepth(Node node) {
        if (node == null)
            return 0;

        // compute the depth of left and right subtrees
        int lDepth = maxDepth(node.left);
        int rDepth = maxDepth(node.right);

        return Math.max(lDepth, rDepth) + 1;
    }

    public static void main(String[] args) {
      
        // Representation of the input tree:
        //     1
        //    / \
        //   2   3
        //  / \
        // 4   5   
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        System.out.println(maxDepth(root));
    }
}
Python
# Python program to find the maximum depth of a binary 
# tree using depth-first search (DFS) approach.

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Returns "maxDepth" which is the number of nodes 
# along the longest path from the root node down 
# to the farthest leaf node.
def maxDepth(node):
    if node is None:
        return 0

    # compute the depth of left and right subtrees
    lDepth = maxDepth(node.left)
    rDepth = maxDepth(node.right)

    return max(lDepth, rDepth) + 1

if __name__ == "__main__":
  
    # Representation of the input tree:
    #     1
    #    / \
    #   2   3
    #  / \
    # 4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    
    print(maxDepth(root))
C#
// C# program to find the maximum depth of a binary 
// tree using depth-first search (DFS) approach.

using System;

class Node {
    public int Data;
    public Node left, right;

    public Node(int val) {
        Data = val;
        left = null;
        right = null;
    }
}

// Returns "MaxDepth" which is the number of nodes 
// along the longest path from the root node down 
// to the farthest leaf node.
class GfG {
  
    static int MaxDepth(Node node) {
        if (node == null)
            return 0;

        // compute the depth of left and right subtrees
        int lDepth = MaxDepth(node.left);
        int rDepth = MaxDepth(node.right);

        return Math.Max(lDepth, rDepth) + 1;
    }

    static void Main() {
      
        // Representation of the input tree:
        //     1
        //    / \
        //   2   3
        //  / \
        // 4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        Console.WriteLine(MaxDepth(root));
    }
}
JavaScript
// JavaScript program to find the maximum depth of
// a binary tree using depth-first search (DFS) approach.

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Returns "maxDepth" which is the number of nodes 
// along the longest path from the root node down 
// to the farthest leaf node.
function maxDepth(node) {
    if (node === null)
        return 0;

    // compute the depth of left and right subtrees
    const lDepth = maxDepth(node.left);
    const rDepth = maxDepth(node.right);

    return Math.max(lDepth, rDepth) + 1;
}

// Representation of the input tree:
//     1
//    / \
//   2   3
//  / \
// 4   5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

console.log(maxDepth(root));

Output
3

Below is the illustration of above approach:

Example: Consider the following tree –

ex-11

maxDepth(’12’) = max(maxDepth(‘8â€ē), maxDepth(’18’)) + 1 = 2 + 1 = 3
because recursively 
maxDepth(‘8’) =  max (maxDepth(‘5â€ē), maxDepth(’11’)) + 1 = 1 + 1
maxDepth(’18’) = max (maxDepth(NULL), maxDepth(‘NULL)) + 1 = 0 + 1 = 1
maxDepth(“5”) = max (maxDepth(NULL), maxDepth(‘NULL)) + 1 = 0 + 1 = 1
maxDepth(“11”) = max (maxDepth(NULL), maxDepth(‘NULL)) + 1 = 0 + 1 = 1

Time Complexity: O(n), where n is the number of nodes in the binary tree, as each node is visited once. (Please see the post on Tree Traversal for details)
Auxiliary Space: O(h) where h is height of the binary tree.

[Expected Approach – 2] Using Level Order Traversal – O(n) Time and O(n) Space

The idea is, if we take a closer look at the depth first traversal, we can notice that after we process the last node of the current level, the next level is completely in the queue. We use this property and insert a special NULL into the queue to indicate end of a level.

Follow the steps below to solve the problem:

  • 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 to indicate end of the first level.
  • 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, it means we have processed the last node of current level and complete next level is in the queue. So we increment depth and insert a NULL for end of the next level.
    • 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++
// C++ program to find the height (depth) of a binary 
// tree using level order traversal approach.

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

struct Node {
    int key;
    Node *left, *right;

    Node(int val) {
        key = val;
        left = nullptr;
        right = nullptr;
    }
};

// Function to find the height (depth) of the tree
int height(Node* root) {
    if (!root) return 0;

    // Initializing a variable to count 
    // the height of the tree
    int depth = 0;

    queue<Node*> q;

    // Pushing the first level element 
    // along with nullptr
    q.push(root);
    q.push(nullptr);

    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();

        // When nullptr is encountered, 
        // increment the depth
        if (curr == nullptr) {
            depth++;

            // If queue still has elements left, 
            // push nullptr again to the queue
            if (!q.empty()) {
                q.push(nullptr);
            }
        } 
        else {
          
            // If nullptr is not encountered, 
            // keep moving
            if (curr->left) q.push(curr->left);
            if (curr->right) q.push(curr->right);
        }
    }
    return depth;
}

int main() {
  
    // Representation of the input tree:
    //     1
    //    / \
    //   2   3
    //  / \
    // 4   5
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);

    cout << height(root);
    return 0;
}
Java
// Java program to find the height (depth) of a binary 
// tree using level order traversal approach.

import java.util.LinkedList;
import java.util.Queue;

class Node {
    int key;
    Node left, right;

    Node(int val) {
        key = val;
        left = null;
        right = null;
    }
}

// Function to find the height (depth) of the tree
class GfG {

    static int height(Node root) {
        if (root == null) return 0;

        // Initializing a variable to count 
        // the height of the tree
        int depth = 0;

        Queue<Node> q = new LinkedList<>();

        // Pushing the first level element 
        // along with null
        q.add(root);
        q.add(null);

        while (!q.isEmpty()) {
            Node curr = q.poll();

            // When null is encountered, 
            // increment the depth
            if (curr == null) {
                depth++;

                // If queue still has elements left, 
                // push null again to the queue
                if (!q.isEmpty()) {
                    q.add(null);
                }
            } 
            else {

                // If null is not encountered, 
                // keep moving
                if (curr.left != null) q.add(curr.left);
                if (curr.right != null) q.add(curr.right);
            }
        }
        return depth;
    }

    public static void main(String[] args) {
      
        // Representation of the input tree:
        //     1
        //    / \
        //   2   3
        //  / \
        // 4   5   
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        System.out.println(height(root));
    }
}
Python
# Python program to find the height (depth) of a binary 
# tree using level order traversal approach.

from collections import deque

class Node:
    def __init__(self, val):
        self.key = val
        self.left = None
        self.right = None

# Function to find the height (depth) of the tree
def height(root):
    if not root:
        return 0

    # Initializing a variable to count 
    # the height of the tree
    depth = 0

    q = deque()

    # Pushing the first level element 
    # along with None
    q.append(root)
    q.append(None)

    while q:
        curr = q.popleft()

        # When None is encountered, 
        # increment the depth
        if curr is None:
            depth += 1

            # If queue still has elements left, 
            # push None again to the queue
            if q:
                q.append(None)
        else:
          
            # If None is not encountered, 
            # keep moving
            if curr.left:
                q.append(curr.left)
            if curr.right:
                q.append(curr.right)
    return depth

if __name__ == "__main__":
  
    # Representation of the input tree:
    #     1
    #    / \
    #   2   3
    #  / \
    # 4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    print(height(root))
C#
// C# program to find the height (depth) of a binary 
// tree using level order traversal approach.

using System;
using System.Collections.Generic;

class Node {
    public int key;
    public Node left, right;

    public Node(int val) {
        key = val;
        left = null;
        right = null;
    }
}

// Function to find the height (depth) of the tree
class GfG {
    static int Height(Node root) {
      
        if (root == null) return 0;

        // Initializing a variable to count 
        // the height of the tree
        int depth = 0;

        Queue<Node> q = new Queue<Node>();

        // Pushing the first level element 
        // along with null
        q.Enqueue(root);
        q.Enqueue(null);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            // When null is encountered, 
            // increment the depth
            if (curr == null) {
                depth++;

                // If queue still has elements left, 
                // push null again to the queue
                if (q.Count > 0) {
                    q.Enqueue(null);
                }
            } 
            else {
              
                // If null is not encountered, 
                // keep moving
                if (curr.left != null) q.Enqueue(curr.left);
                if (curr.right != null) q.Enqueue(curr.right);
            }
        }
        return depth;
    }

    static void Main() {
      
        // Representation of the input tree:
        //     1
        //    / \
        //   2   3
        //  / \
        // 4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        Console.WriteLine(Height(root));
    }
}
JavaScript
// JavaScript function to find the height (depth)
// of a binary tree using level order traversal approach.

class Node {
    constructor(val) {
        this.key = val;
        this.left = null;
        this.right = null;
    }
}

// Function to find the height (depth) of the tree
function height(root) {
    if (root === null) return 0;

    // Initializing a variable to count 
    // the height of the tree
    let depth = 0;
    let q = [];

    // Pushing the first level element 
    // along with null
    q.push(root);
    q.push(null);

    while (q.length > 0) {
        let curr = q.shift();

        // When null is encountered, 
        // increment the depth
        if (curr === null) {
            depth++;
            
            // If queue still has elements left, 
            // push null again to the queue
            if (q.length > 0) {
                q.push(null);
            }
        } 
        else {
        
            // If null is not encountered, 
            // keep moving
            if (curr.left) q.push(curr.left);
            if (curr.right) q.push(curr.right);
        }
    }
    return depth;
}

// Representation of the input tree:
//     1
//    / \
//   2   3
//  / \
// 4   5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
console.log(height(root));

Output
3

Time Complexity: O(n), where n is the number of nodes, as each node is processed once.
Auxiliary Space: O(n), since in the worst case, all nodes of the last level (around n/2) could be in the queue simultaneously.

[Alternate Approach] Using Level Order Traversal – O(n) Time and O(n) Space

This method also uses the same concept that when we process the last node of a current level, the next level is completely in the queue. Instead of adding a 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 to find the height (depth) of a binary 
// tree using level order traversal approach 2.
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int key;
    Node *left, *right;
    Node(int val) {
        key = val;
        left = nullptr;
        right = nullptr;
    }
};

// Function to find the height (depth)
// of the tree
int height(Node* root) {
    if (!root) return 0;

    // Initializing a queue to traverse
    // the tree level by level
    queue<Node*> q;
    q.push(root);
    int h = 0;

    // Loop until the queue is empty
    while (!q.empty()) {
        int size = q.size();

        // Traverse all nodes at the current level
        for (int i = 0; i < size; i++) {
            Node* temp = q.front();
            q.pop();
            if (temp->left) q.push(temp->left);
            if (temp->right) q.push(temp->right);
        }

        // Increment height after traversing each level
        h++;
    }
    return h;
}

int main() {
  
    // Representation of the input tree:
    //     1
    //    / \
    //   2   3
    //  / \
    // 4   5
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);

    cout << height(root);
    return 0;
}
Java
// Java program to find the height (depth) of a binary 
// tree using level order traversal approach 2.
import java.util.LinkedList;
import java.util.Queue;

class Node {
    int key;
    Node left, right;

    Node(int val) {
        key = val;
        left = null;
        right = null;
    }
}

// Function to find the height (depth) of the tree
class GfG {
    static int height(Node root) {
        if (root == null) return 0;

        // Initializing a queue to traverse
        // the tree level by level
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        int h = 0;

        // Loop until the queue is empty
        while (!q.isEmpty()) {
            int size = q.size();

            // Traverse all nodes at the current level
            for (int i = 0; i < size; i++) {
                Node temp = q.poll();

                if (temp.left != null) q.add(temp.left);
                if (temp.right != null) q.add(temp.right);
            }

            // Increment height after traversing each level
            h++;
        }
        return h;
    }

    public static void main(String[] args) {
      
        // Representation of the input tree:
        //     1
        //    / \
        //   2   3
        //  / \
        // 4   5   
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        System.out.println(height(root));
    }
}
Python
# Python program to find the height (depth) of a binary 
# tree using level order traversal approach 2.
from collections import deque

class Node:
    def __init__(self, val):
        self.key = val
        self.left = None
        self.right = None

# Function to find the height (depth) of the tree
def height(root):
    if root is None:
        return 0

    # Initializing a queue to traverse
    # the tree level by level
    q = deque([root])
    h = 0

    # Loop until the queue is empty
    while q:
        size = len(q)

        # Traverse all nodes at the current level
        for _ in range(size):
            temp = q.popleft()

            if temp.left:
                q.append(temp.left)
            if temp.right:
                q.append(temp.right)

        # Increment height after traversing each level
        h += 1

    return h

if __name__ == "__main__":
  
    # Representation of the input tree:
    #     1
    #    / \
    #   2   3
    #  / \
    # 4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    print(height(root))
C#
// C# program to find the height (depth) of a binary 
// tree using level order traversal approach 2.
using System;
using System.Collections.Generic;

class Node {
    public int key;
    public Node left, right;

    public Node(int val) {
        key = val;
        left = null;
        right = null;
    }
}

// Function to find the height (depth) of the tree
class GfG {
    static int Height(Node root) {
      
        if (root == null) return 0;

        // Initializing a queue to traverse
        // the tree level by level
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        int h = 0;

        // Loop until the queue is empty
        while (q.Count > 0) {
            int size = q.Count;

            // Traverse all nodes at the current level
            for (int i = 0; i < size; i++) {
                Node temp = q.Dequeue();

                if (temp.left != null) q.Enqueue(temp.left);
                if (temp.right != null) q.Enqueue(temp.right);
            }

            // Increment height after traversing each level
            h++;
        }
        return h;
    }

    static void Main() {
      
        // Representation of the input tree:
        //     1
        //    / \
        //   2   3
        //  / \
        // 4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        Console.WriteLine(Height(root));
    }
}
JavaScript
// Javascript program to find the height (depth) of a binary 
// tree using level order traversal approach 2.
class Node {
    constructor(val) {
        this.key = val;
        this.left = null;
        this.right = null;
    }
}

// Function to find the height (depth) of the tree
function height(root) {
    if (root === null) return 0;

    // Initializing a queue to traverse
    // the tree level by level
    let q = [root];
    let h = 0;

    // Loop until the queue is empty
    while (q.length > 0) {
        let size = q.length;

        // Traverse all nodes at the current level
        for (let i = 0; i < size; i++) {
            let temp = q.shift();

            if (temp.left) q.push(temp.left);
            if (temp.right) q.push(temp.right);
        }

        // Increment height after traversing each level
        h++;
    }
    return h;
}

// Representation of the input tree:
//     1
//    / \
//   2   3
//  / \
// 4   5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
console.log(height(root));

Output
3

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

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 n
15+ min read
Sum of nodes at maximum depth of a Binary Tree
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 While traversing the nodes compare the level of the node with max_level (Maximum level
15+ min read
Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from the root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7Input : root(of above tree)Output : 22Explanation:Nodes at maximum depth are 4, 5, 6, 7. So, the sum of these nodes = 22Approach: There exists a recursive approach to this problem. This can also be solved
8 min read
Maximum height of an elevation possible such that adjacent matrix cells have a difference of at most height 1
Given a matrix mat][][] of size M x N which represents the topographic map of a region, and 0 denotes land and 1 denotes elevation, the task is to maximize the height in the matrix by assigning each cell a non-negative height such that the height of a land cell is 0 and two adjacent cells must have an absolute height difference of at most 1. Exampl
12 min read
Check if a given Binary Tree is height balanced like a Red-Black Tree
In a Red-Black Tree, the maximum height of a node is at most twice the minimum height (The four Red-Black tree properties make sure this is always followed). Given a Binary Search Tree, we need to check for following property. For every node, length of the longest leaf to node path has not more than twice the nodes on shortest path from node to lea
9 min read
Find Minimum Depth of a Binary Tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Binary Tree is also 2. 10 / 5 Recommended PracticeMi
15 min read
Replace node with depth in a binary tree
Given a binary tree, replace each node with its depth value. For example, consider the following tree. Root is at depth 0, change its value to 0 and next level nodes are at depth 1 and so on. 3 0 / \ / \ 2 5 == >; 1 1 / \ / \ 1 4 2 2 The idea is to traverse tree starting from root. While traversing pass depth of node as parameter. We can track d
11 min read
Depth of the deepest odd level node in Binary Tree
Given a Binary tree, find out depth of the deepest odd level leaf node. Take root level as depth 1. Examples:  Input : Output : 5Input : 10 / \ 28 13 / \ 14 15 / \ 23 24Output : 3We can traverse the tree starting from the root level and keep curr_level of the node. Increment the curr_level each time we go to left or a right subtree. Return the max
14 min read
Calculate depth of a full Binary tree from Preorder
Given the preorder sequence of a full binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters. 'l' denotes the leaf node'n' denotes internal nodeThe given tree can be seen as a full binary tree where every node has 0 or two children. The two children of a node can be 'n' or
5 min read
Minimum valued node having maximum depth in an N-ary Tree
Given a tree of N nodes, the task is to find the node having maximum depth starting from the root node, taking the root node at zero depth. If there are more than 1 maximum depth node, then find the one having the smallest value. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 4 Explanation: For this tree: Height of Node 1 - 0, Height of Node 2 - 1, Hei
5 min read
Maximum height of the binary search tree created from the given array
Given an array arr[] of N integers, the task is to make two binary search trees. One while traversing from the left side of the array and another while traversing from the right and find which tree has a greater height.Examples: Input: arr[] = {2, 1, 3, 4} Output: 0 BST starting from first index BST starting from last index 2 4 / \ / 1 3 3 \ / 4 1
10 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Comparison between Height Balanced Tree and Weight Balanced Tree
What is Height Balanced Tree? Self-Balancing binary search trees are the height-balanced binary tree is one for which at every node, the absolute value of the difference in heights of the left and right subtree is no larger than one. An empty tree is height-balanced. A non-empty binary tree T is balanced if: The left subtree of T is balanced.The ri
4 min read
Replace every node with depth in N-ary Generic Tree
Given an array arr[] representing a Generic(N-ary) tree. The task is to replace the node data with the depth(level) of the node. Assume level of root to be 0. Array Representation: The N-ary tree is serialized in the array arr[] using level order traversal as described below:   The input is given as a level order traversal of N-ary Tree.The first e
15+ min read
Depth of an N-Ary tree
Given an n-ary tree containing positive node values, the task is to find the depth of the tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branches or children for each node. Examples: Input: Out
5 min read
Iterative Method to find Height of Binary Tree
There are two conventions to define the height of a Binary Tree Number of nodes on the longest path from the root to the deepest node. Number of edges on the longest path from the root to the deepest node. In this post, the first convention is followed. For example, the height of the below tree is 3. The recursive method to find the height of the B
8 min read
Height of binary tree considering even level leaves only
Find the height of the binary tree given that only the nodes on the even levels are considered valid leaf nodes. The height of a binary tree is the number of edges between the tree's root and its furthest leaf. But what if we bring a twist and change the definition of a leaf node? Let us define a valid leaf node as the node that has no children and
8 min read
Print the nodes of the Binary Tree whose height is a Prime number
Given a binary tree, our task is to print the nodes whose height is a prime number starting from the root node. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 4 5 Explanation: For this tree: Height of Node 1 - 0, Height of Node 2 - 1, Height of Node 3 - 1, Height of Node 4 - 2, Height of Node 5 - 2. Hence, the nodes whose height is a prime number are 4
8 min read
Calculate height of Binary Tree using Inorder and Level Order Traversal
Given inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it. Example: Input : Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output : 4 The binary tree that ca
12 min read
Introduction to Height Balanced Binary Tree
A height-balanced binary tree is defined as a binary tree in which the height of the left and the right subtree of any node differ by not more than 1. AVL tree, red-black tree are examples of height-balanced trees. Conditions for Height-Balanced Binary Tree: Following are the conditions for a height-balanced binary tree: The difference between the
5 min read
Construct a Perfect Binary Tree with given Height
Given an integer N, the task is to generate a perfect binary tree with height N such that each node has a value that is the same as its depth. Return the inorder traversal of the generated binary tree. A Perfect binary tree is a type of binary tree where every internal node has exactly two child nodes and all leaf nodes are at same level. Examples:
9 min read
Find Height of Binary Tree represented by Parent array
A given array represents a tree in such a way that the array value gives the parent node of that particular index. The value of the root node index would always be -1. Find the height of the tree. The height of a Binary Tree is the number of nodes on the path from the root to the deepest leaf node, and the number includes both root and leaf. Input:
13 min read
Height of a complete binary tree (or Heap) with N nodes
Consider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we take a few examples, we can notice that the value of
3 min read
Find height of a special binary tree whose leaf nodes are connected
Given a special binary tree whose leaf nodes are connected to form a circular doubly linked list, find its height. For example, 1 / \ 2 3 / \ 4 5 / 6 In the above binary tree, 6, 5 and 3 are leaf nodes and they form a circular doubly linked list. Here, the left pointer of leaf node will act as a previous pointer of circular doubly linked list and i
9 min read
Print middle level of perfect binary tree without finding height
Given a perfect binary tree, print nodes of middle level without computing its height. A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level. Output : 4 5 6 7 The idea is similar to method 2 of finding middle of singly linked list.Use fast and slow (or tortoise) pointer
7 min read
Relationship between number of nodes and height of binary tree
Prerequisite - Binary Tree Data Structure In this article, we will discuss various cases for relationship between number of nodes and height of binary tree. Before understanding this article, you should have basic idea about binary trees and their properties. The height of the binary tree is the longest path from root node to any leaf node in the t
3 min read
Maximum height of Tree when any Node can be considered as Root
Given a tree with N nodes and N-1 edges, find out the maximum height of the tree when any node in the tree is considered as the root of the tree. The above diagram represents a tree with 11 nodes and 10 edges and the path that gives us the maximum height when node 1 is considered as a root. The maximum height is 3. In the above diagram, when 2 is c
15 min read
Find maximum depth of nested parenthesis in a string
We are given a string having parenthesis like below “( ((X)) (((Y))) )” We need to find the maximum depth of balanced parenthesis, like 4 in the above example. Since ‘Y’ is surrounded by 4 balanced parentheses. If parenthesis is unbalanced then return -1. Examples : Input : S = "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)"; Output : 4 Input : S = "( p((q))
9 min read
Count of BSTs having N nodes and maximum depth equal to H
Given two integers N and H, the task is to find the count of distinct Binary Search Trees consisting of N nodes where the maximum depth or height of the tree is equal to H. Note: The height of BST with only the root node is 0. Examples: Input: N = 2, H = 1Output: 2Explanation: The two BST's are : Input: N = 3, H = 2Output: 4Explanation: The four BS
15+ min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
three90RightbarBannerImg