Minimum Depthof Binary Tree Algorithm
The Minimum Depth of Binary Tree Algorithm is a widely-used technique in computer science for determining the shortest distance, or minimum number of edges, between the root node and the nearest leaf node in a binary tree data structure. A binary tree is a hierarchical data structure consisting of nodes, each containing a value and having at most two child nodes, referred to as the left child and the right child. The root node is the topmost node in the tree, and leaf nodes are nodes that do not have any children. The depth of a node is the number of edges in the path from the root to that node, and the depth of the tree is the maximum depth of any of its nodes. The minimum depth of a binary tree, on the other hand, is the shortest path from the root to any leaf node, traversing through the child nodes along the way.
To compute the minimum depth of a binary tree, a common approach is to use a depth-first search (DFS) or breadth-first search (BFS) traversal algorithm. In the case of DFS, the algorithm starts at the root node and explores as far as possible along each branch before backtracking. When a leaf node is encountered, the depth of that node is calculated, and the minimum depth is updated if the current node's depth is less than the current minimum depth. For BFS, the algorithm explores all the nodes at the current depth before moving on to the nodes at the next depth level. The first time a leaf node is encountered during the search, the algorithm terminates, and the depth of that node is the minimum depth. Both DFS and BFS can be implemented using recursion or iteration, with the latter often utilizing a queue or stack data structure to keep track of the nodes to be processed.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
int lf = INT_MAX, rt = INT_MAX;
if (root->left)
lf = 1 + minDepth(root->left);
if (root->right)
rt = 1 + minDepth(root->right);
return min(lf, rt);
}
};