[Geeks for Geeks] Minimum Depth of a Binary Tree

Minimum Depth of a Binary Tree

Given a binary tree, find its minimum depth.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* The Node structure is
struct Node
{
int data;
Node* left;
Node* right;
}; */

class Solution{
public:
/*You are required to complete this method*/
int minDepth(Node *root, int dep = 1) {
if(!root->left and !root->right) return dep;
int res = INT_MAX;
if(root->left) res = min(res, minDepth(root->left, dep + 1));
if(root->right) res = min(res, minDepth(root->right, dep + 1));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/minimum-depth-of-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.