[LeetCode] Minimum Depth of Binary Tree

111. Minimum Depth of 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.

Note: A leaf is a node with no children.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
void dfs(TreeNode* node, int& res, int dep) {
if(!node->left and !node->right) res = min(res, dep);
else {
if(node->left) dfs(node->left, res, dep + 1);
if(node->right) dfs(node->right, res, dep + 1);
}
}
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
int res = INT_MAX;
dfs(root, res, 1);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/10/PS/LeetCode/minimum-depth-of-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.