The Wayback Machine - https://web.archive.org/web/20240821233411/https://www.geeksforgeeks.org/find-minimum-depth-of-a-binary-tree/
Open In App

Find Minimum Depth of a Binary Tree

Last Updated : 25 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 
 

Example Tree

Note that the path must end on a leaf node. For example, the minimum depth of below Binary Tree is also 2. 

          10
        /    
      5  

Method 1: The idea is to traverse the given Binary Tree. For every node, check if it is a leaf node. If yes, then return 1. If not leaf node then if the left subtree is NULL, then recur for the right subtree. And if the right subtree is NULL, then recur for the left subtree. If both left and right subtrees are not NULL, then take the minimum of two depths.

Below is implementation of the above idea.  

C++




// C++ program to find minimum depth of a given Binary Tree
#include<bits/stdc++.h>
using namespace std;
 
// A BT Node
struct Node
{
    int data;
    struct Node* left, *right;
};
 
int minDepth(Node *root)
{
    // Corner case. Should never be hit unless the code is
    // called on root = NULL
    if (root == NULL)
        return 0;
 
    // Base case : Leaf Node. This accounts for height = 1.
    if (root->left == NULL && root->right == NULL)
    return 1;
   
    int l = INT_MAX, r = INT_MAX;
    // If left subtree is not NULL, recur for left subtree
   
    if (root->left)
    l = minDepth(root->left);
 
    // If right subtree is not NULL, recur for right subtree
    if (root->right)
    r =  minDepth(root->right);
 
  //height will be minimum of left and right height +1
    return min(l , r) + 1;
}
 
// Utility function to create new Node
Node *newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Driver program
int main()
{
    // Let us construct the Tree shown in the above figure
    Node *root     = newNode(1);
    root->left     = newNode(2);
    root->right     = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    cout <<"The minimum depth of binary tree is : "<< minDepth(root);
    return 0;
}


C




// C program to find minimum depth of a given Binary Tree
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
 
// A BT Node
typedef struct Node {
    int data;
    struct Node *left, *right;
} Node;
 
int min(int num1, int num2)
{
    return (num1 > num2) ? num2 : num1;
}
 
int minDepth(Node* root)
{
    // Corner case. Should never be hit unless the code is
    // called on root = NULL
    if (root == NULL)
        return 0;
 
    // Base case : Leaf Node. This accounts for height = 1.
    if (root->left == NULL && root->right == NULL)
        return 1;
    int l = INT_MAX;
    int r = INT_MIN;
    // If left subtree is not NULL, recur for left subtree
 
    if (root->left)
        l = minDepth(root->left);
 
    // If right subtree is not NULL, recur for right subtree
    if (root->right)
        r = minDepth(root->right);
 
    // height will be minimum of left and right height +1
    return min(l, r) + 1;
}
 
// Utility function to create new Node
Node* newNode(int data)
{
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = data;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Driver program
int main()
{
    // Let us construct the Tree shown in the above figure
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    printf("The minimum depth of binary tree is : %d",
           minDepth(root));
    return 0;
}
 
// This code is contributed by aditya kumar (adityakumar129)


Java




/* Java implementation to find minimum depth
   of a given Binary tree */
 
/* Class containing left and right child of current
node and key value*/
class Node
{
    int data;
    Node left, right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
public class BinaryTree
{
    //Root of the Binary Tree
    Node root;
 
    int minimumDepth()
    {
        return minimumDepth(root);
    }
 
    /* Function to calculate the minimum depth of the tree */
    int minimumDepth(Node root)
    {
        // Corner case. Should never be hit unless the code is
        // called on root = NULL
        if (root == null)
            return 0;
 
        // Base case : Leaf Node. This accounts for height = 1.
        if (root.left == null && root.right == null)
            return 1;
 
        // If left subtree is NULL, recur for right subtree
        if (root.left == null)
            return minimumDepth(root.right) + 1;
 
        // If right subtree is NULL, recur for left subtree
        if (root.right == null)
            return minimumDepth(root.left) + 1;
 
        return Math.min(minimumDepth(root.left),
                        minimumDepth(root.right)) + 1;
    }
 
    /* Driver program to test above functions */
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
 
        System.out.println("The minimum depth of "+
          "binary tree is : " + tree.minimumDepth());
    }
}


Python3




# Python program to find minimum depth of a given Binary Tree
 
# Tree node
class Node:
    def __init__(self , key):
        self.data = key
        self.left = None
        self.right = None
 
def minDepth(root):
    # Corner Case.Should never be hit unless the code is
    # called on root = NULL
    if root is None:
        return 0
     
    # Base Case : Leaf node.This accounts for height = 1
    if root.left is None and root.right is None:
        return 1
     
    # If left subtree is Null, recur for right subtree
    if root.left is None:
        return minDepth(root.right)+1
     
    # If right subtree is Null , recur for left subtree
    if root.right is None:
        return minDepth(root.left) +1
     
    return min(minDepth(root.left), minDepth(root.right))+1
 
# Driver Program
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print (minDepth(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)       


C#




using System;
 
/* C# implementation to find minimum depth
   of a given Binary tree */
 
/* Class containing left and right child of current
node and key value*/
public class Node
{
    public int data;
    public Node left, right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
public class BinaryTree
{
    //Root of the Binary Tree
    public Node root;
 
    public virtual int minimumDepth()
    {
        return minimumDepth(root);
    }
 
    /* Function to calculate the minimum depth of the tree */
    public virtual int minimumDepth(Node root)
    {
        // Corner case. Should never be hit unless the code is
        // called on root = NULL
        if (root == null)
        {
            return 0;
        }
 
        // Base case : Leaf Node. This accounts for height = 1.
        if (root.left == null && root.right == null)
        {
            return 1;
        }
 
        // If left subtree is NULL, recur for right subtree
        if (root.left == null)
        {
            return minimumDepth(root.right) + 1;
        }
 
        // If right subtree is NULL, recur for left subtree
        if (root.right == null)
        {
            return minimumDepth(root.left) + 1;
        }
 
        return Math.Min(minimumDepth(root.left), minimumDepth(root.right)) + 1;
    }
 
    /* Driver program to test above functions */
    public static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
 
        Console.WriteLine("The minimum depth of binary tree is : " + tree.minimumDepth());
    }
}
 
  // This code is contributed by Shrikant13


Javascript




<script>
/* javascript implementation to find minimum depth
   of a given Binary tree */
 
/* Class containing left and right child of current
node and key value*/
class Node {
    constructor(item) {
        this.data = item;
        this.left = this.right = null;
    }
}
    // Root of the Binary Tree
    let root;
 
    function minimumDepth() {
        return minimumDepth(root);
    }
 
    /* Function to calculate the minimum depth of the tree */
    function minimumDepth( root) {
        // Corner case. Should never be hit unless the code is
        // called on root = NULL
        if (root == null)
            return 0;
 
        // Base case : Leaf Node. This accounts for height = 1.
        if (root.left == null && root.right == null)
            return 1;
 
        // If left subtree is NULL, recur for right subtree
        if (root.left == null)
            return minimumDepth(root.right) + 1;
 
        // If right subtree is NULL, recur for left subtree
        if (root.right == null)
            return minimumDepth(root.left) + 1;
 
        return Math.min(minimumDepth(root.left), minimumDepth(root.right)) + 1;
    }
 
    /* Driver program to test above functions */
     
         
        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);
 
        document.write("The minimum depth of "
        + "binary tree is : " + minimumDepth(root));
 
 
// This code contributed by aashish1995
</script>


Output

The minimum depth of binary tree is : 2

Time Complexity: O(n), as it traverses the tree only once. 
Auxiliary Space: O(h), where h is the height of the tree, this space is due to the recursive call stack.

Method 2: The above method may end up with complete traversal of Binary Tree even when the topmost leaf is close to root. A Better Solution is to do Level Order Traversal. While doing traversal, returns depth of the first encountered leaf node.

Below is the implementation of this solution.  

C++




// C++ program to find minimum depth of a given Binary Tree
#include <bits/stdc++.h>
using namespace std;
 
// A Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
    Node(int d = 0)
        : data{ d }
    {
    }
};
 
// A queue item (Stores pointer to node and an integer)
struct qItem {
    Node* node;
    int depth;
};
 
// Iterative method to find minimum depth of Binary Tree
int minDepth(Node* root)
{
    // Corner Case
    if (root == NULL)
        return 0;
 
    // Create an empty queue for level order traversal
    queue<qItem> q;
 
    // Enqueue Root and initialize depth as 1
    qItem qi = { root, 1 };
    q.push(qi);
 
    // Do level order traversal
    while (q.empty() == false) {
        // Remove the front queue item
        qi = q.front();
        q.pop();
 
        // Get details of the remove item
        Node* node = qi.node;
        int depth = qi.depth;
 
        // If this  is the first leaf node seen so far
        // Then return its depth as answer
        if (node->left == NULL && node->right == NULL)
            return depth;
 
        // If left subtree is not NULL, add it to queue
        if (node->left != NULL) {
            qi.node = node->left;
            qi.depth = depth + 1;
            q.push(qi);
        }
 
        // If right subtree is not NULL, add it to queue
        if (node->right != NULL) {
            qi.node = node->right;
            qi.depth = depth + 1;
            q.push(qi);
        }
    }
    return 0;
}
 
// Utility function to create a new tree Node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Driver program to test above functions
int main()
{
    // Let us create binary tree shown in above diagram
    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 << minDepth(root);
    return 0;
}


Java




// Java program to find minimum depth
// of a given Binary Tree
import java.util.*;
public class GFG
{
     
// A binary Tree node
static class Node
{
    int data;
    Node left, right;
}
 
// A queue item (Stores pointer to
// node and an integer)
static class qItem
{
    Node node;
    int depth;
 
    public qItem(Node node, int depth)
    {
        this.node = node;
        this.depth = depth;
    }
}
 
// Iterative method to find
// minimum depth of Binary Tree
static int minDepth(Node root)
{
    // Corner Case
    if (root == null)
        return 0;
 
    // Create an empty queue for level order traversal
    Queue<qItem> q = new LinkedList<>();
 
    // Enqueue Root and initialize depth as 1
    qItem qi = new qItem(root, 1);
    q.add(qi);
 
    // Do level order traversal
    while (q.isEmpty() == false)
    {
        // Remove the front queue item
        qi = q.peek();
        q.remove();
     
        // Get details of the remove item
        Node node = qi.node;
        int depth = qi.depth;
     
        // If this is the first leaf node seen so far
        // Then return its depth as answer
        if (node.left == null && node.right == null)
            return depth;
     
        // If left subtree is not null,
        // add it to queue
        if (node.left != null)
        {
            qi.node = node.left;
            qi.depth = depth + 1;
            q.add(qi);
        }
     
        // If right subtree is not null,
        // add it to queue
        if (node.right != null)
        {
            qi.node = node.right;
            qi.depth = depth + 1;
            q.add(qi);
        }
    }
    return 0;
}
 
// Utility function to create a new tree Node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// Driver Code
public static void main(String[] args)
{
    // Let us create binary tree shown in above diagram
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
 
    System.out.println(minDepth(root));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python program to find minimum depth of a given Binary Tree
 
# A Binary Tree node
class Node:
    # Utility to create new node
    def __init__(self , data):
        self.data = data
        self.left = None
        self.right = None
 
def minDepth(root):
    # Corner Case
    if root is None:
         return 0
 
    # Create an empty queue for level order traversal
    q = []
     
    # Enqueue root and initialize depth as 1
    q.append({'node': root , 'depth' : 1})
 
    # Do level order traversal
    while(len(q)>0):
        # Remove the front queue item
        queueItem = q.pop(0)
     
        # Get details of the removed item
        node = queueItem['node']
        depth = queueItem['depth']
        # If this is the first leaf node seen so far
        # then return its depth as answer
        if node.left is None and node.right is None:   
            return depth
         
        # If left subtree is not None, add it to queue
        if node.left is not None:
            q.append({'node' : node.left , 'depth' : depth+1})
 
        # if right subtree is not None, add it to queue
        if node.right is not None: 
            q.append({'node': node.right , 'depth' : depth+1})
 
# Driver program to test above function
# Lets construct a binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print (minDepth(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




// C# program to find minimum depth
// of a given Binary Tree
using System;
using System.Collections.Generic;
     
class GFG
{
     
// A binary Tree node
public class Node
{
    public int data;
    public Node left, right;
}
 
// A queue item (Stores pointer to
// node and an integer)
public class qItem
{
    public Node node;
    public int depth;
 
    public qItem(Node node, int depth)
    {
        this.node = node;
        this.depth = depth;
    }
}
 
// Iterative method to find
// minimum depth of Binary Tree
static int minDepth(Node root)
{
    // Corner Case
    if (root == null)
        return 0;
 
    // Create an empty queue for
    // level order traversal
    Queue<qItem> q = new Queue<qItem>();
 
    // Enqueue Root and initialize depth as 1
    qItem qi = new qItem(root, 1);
    q.Enqueue(qi);
 
    // Do level order traversal
    while (q.Count != 0)
    {
        // Remove the front queue item
        qi = q.Peek();
        q.Dequeue();
     
        // Get details of the remove item
        Node node = qi.node;
        int depth = qi.depth;
     
        // If this is the first leaf node
        // seen so far.
        // Then return its depth as answer
        if (node.left == null &&
            node.right == null)
            return depth;
     
        // If left subtree is not null,
        // add it to queue
        if (node.left != null)
        {
            qi.node = node.left;
            qi.depth = depth + 1;
            q.Enqueue(qi);
        }
     
        // If right subtree is not null,
        // add it to queue
        if (node.right != null)
        {
            qi.node = node.right;
            qi.depth = depth + 1;
            q.Enqueue(qi);
        }
    }
    return 0;
}
 
// Utility function to create a new tree Node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Let us create binary tree
    // shown in above diagram
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
 
    Console.WriteLine(minDepth(root));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// Javascript program to find minimum depth
// of a given Binary Tree
class Node
{
     
    // Utility function to create a new tree Node
    constructor(data)
    {
        this.data = data;
        this.left = this.right = null;
    }
}
 
class qItem
{
    constructor(node,depth)
    {
        this.node = node;
        this.depth = depth;
    }
}
 
function minDepth(root)
{
     
    // Corner Case
    if (root == null)
        return 0;
         
    // Create an empty queue for
    // level order traversal
    let q = [];
  
    // Enqueue Root and initialize depth as 1
    let qi = new qItem(root, 1);
    q.push(qi);
  
    // Do level order traversal
    while (q.length != 0)
    {
         
        // Remove the front queue item
        qi = q.shift();
         
        // Get details of the remove item
        let node = qi.node;
        let depth = qi.depth;
      
        // If this is the first leaf node seen so far
        // Then return its depth as answer
        if (node.left == null && node.right == null)
            return depth;
      
        // If left subtree is not null,
        // add it to queue
        if (node.left != null)
        {
            qi.node = node.left;
            qi.depth = depth + 1;
            q.push(qi);
        }
      
        // If right subtree is not null,
        // add it to queue
        if (node.right != null)
        {
            qi.node = node.right;
            qi.depth = depth + 1;
            q.push(qi);
        }
    }
    return 0;
}
 
// Driver Code
 
// Let us create binary tree shown
// in above diagram
let 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);
 
document.write(minDepth(root));
 
// This code is contributed by rag2127
 
</script>


Output

2

Time Complexity: O(n), where n is the number of nodes in the given binary tree. This is due to the fact that we are visiting each node once.
Auxiliary Space: O(n), as we need to store the elements in a queue for level order traversal.



Previous Article
Next Article

Similar Reads

Calculate depth of a full Binary tree from Preorder
Given preorder of a 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'n' denotes internal node The 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 'n' or 'l' or mix of both. Exam
5 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 == &gt;; 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
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
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
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 | 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 Depth or Height of Binary Tree
Given a binary tree, the task is to find the maxim 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.  Example 1: The height of the below binary tree is 3 Example 2: The height of the below binary tree is 4Corner Cases: Maximum Depth of an empty tree is 0 and of a tree with s
15+ 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
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
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Find the minimum Sub-tree with target sum in a Binary search tree
Given a binary tree and a target, find the number of nodes in the minimum sub-tree with the given sum equal to the target which is also a binary search tree. Examples: Input: 13 / \ 5 23 / \ / \ N 17 N N / 16Target: 38Output: 3Explanation: 5, 17, 16 is the smallest subtree with length 3. Input: 7 / \ N 23 / \ 10 23 / \ / \ N 17 N NTarget: 73Output:
9 min read
Depth of an N-Ary tree
Given an N-Ary tree, find depth of the tree. An N-Ary tree is a tree in which nodes can have at most N children. Algorithm Here is the algorithm for finding the depth of an N-Ary tree: 1)Define a struct for the nodes of the N-ary tree with a key and a vector of pointers to its child nodes. 2)Create a utility function to create a new node with the g
6 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
Sum of minimum element at each depth of a given non cyclic graph
Given a non-cyclic graph having V nodes and E edges and a source node S, the task is to calculate the sum of the minimum element at each level from source node S in the given graph.Examples: Input: S = 0, Below is the given graph Output: 5 Explanation: There is only one node at depth 0 i.e. 0. At depth 1 there are 3 nodes 1, 2, 3, and minimum of th
11 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
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
11 min read
Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes
Given a Binary Tree, the task is to convert the given Binary Tree to the Symmetric Tree by adding the minimum number of nodes in the given Tree. Examples: Input: Output: Input: Output: Approach: To solve this problem, follow the below steps: Make a function buildSymmetricTree which will accept two parameters root1 and root2.Here, root1 and root2, a
8 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
Article Tags :
Practice Tags :
three90RightbarBannerImg