[leetcode]111. Minimum Depth of Binary Tree
Analysis
组会又被怼了—— [哎~]
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.
这题是求二叉树的最短深度
需要注意的是当二叉树只有一根树枝的时候要用
max(minDepth(root->left), minDepth(root->right))+1
因为没注意到就提交然后没有A,后来看了这个博客才发现的:https://blog.csdn.net/nomasp/article/details/50572933 讲的比较清楚
Implement
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
if(root->left!=NULL && root->right!=NULL)
return min(minDepth(root->left), minDepth(root->right))+1;
return max(minDepth(root->left), minDepth(root->right))+1;
}
};