class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int max=0;
int flag=0,flag1=1;
int minDepth(TreeNode *root) {
// write your code here
if(root==NULL)return 0;
flag+=1;
if(root->right==NULL&&root->left==NULL){
if(flag1==1){max=flag;flag1=0;}
if(max>flag)max=flag;
}
if(root->right!=NULL)minDepth(root->right);
if(root->left!=NULL)minDepth(root->left);
flag-=1;
return max;
}
};
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
解题思路:和最大深度类似,dfs遍历更新min,最后输出最小的min。