您的位置:首页 > 其它

LeetCode 111 Minimum Depth of Binary Tree(DFS)

2017-05-19 11:10 417 查看
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.

题目大意:给出一个二叉树,求从根节点到叶节点的最小深度。

解题思路:直接DFS,和LeetCode 104 Maximum Depth of Bianry Tree类似,只不过多了些判断。

代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/

int minDepth(struct TreeNode* root) {
if(root == NULL) return 0;
else if(root->left && !root->right) return 1 + minDepth(root->left);
else if(root->right && !root->left) return 1 + minDepth(root->right);
else{
int left = 1 + minDepth(root->left);
int right = 1 + minDepth(root->right);
return left < right ? left : right;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode