2020年5月23日
LeetCode 111. Minimum Depth of Binary Tree
C++, LeetCode, 算法, 编程
0 Comments
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.
Example:
Given binary tree [3, 9, 20, null, null, 15, 7] ,
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
解析:求二叉树的最小深度,采用深度优先的思路。因为这里求的最小深度指的是根节点到叶节点的路径,所以如果某个节点左子树为空,则返回右子树的最小深度+1.如果左右子树都不为空,则返回min(left_len, right_len)+1。
代码如下:
/**
* 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 {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
if(!root->left)
return 1 + minDepth(root->right);
if(!root->right)
return 1 + minDepth(root->left);
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};