二叉树的最小深度
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
标签
这道题很有趣的地方是,要考虑斜树怎么解决,另外和只有一个节点的情况。
一开始用了常规思路,斜数直接WA。
顺便提一下,INT_MAX和INT_MIN是<limits.h>中int的最大值和最小值。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: The root of binary tree
* @return: An integer
*/
int minDepth(TreeNode * root) {
// write your code here
if(root==NULL)
return 0;
if(!root->left&&!root->right)
return 1;
int l=minDepth(root->left);
int r=minDepth(root->right);
if(l==0)
l=INT_MAX;
if(r==0)
r=INT_MAX;
return min(l,r)+1;
}
};
INT_MAX可解决斜树返回1的问题。
转载于:https://www.cnblogs.com/ygtzds/p/7554507.html