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;
}
}
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 111 Minimum Depth of Binary Tree (DFS)
- leetcode 111 Minimum Depth of Binary Tree(DFS)
- LeetCode 111 Minimum Depth of Binary Tree(二叉树的最短深度)(BT、DFS)(*)
- leetcode 111 Minimum Depth of Binary Tree C++
- LeetCode 111 Minimum Depth of Binary Tree
- LeetCode111—Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- leetcode[111]Minimum Depth of Binary Tree
- LeetCode111:Minimum Depth of Binary Tree
- LeetCode 111 Minimum Depth of Binary Tree
- leetcode(111):Minimum Depth of Binary Tree
- Leetcode 111 Minimum Depth of Binary Tree
- leetcode 111:Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- LeetCode111 Minimum Depth of Binary Tree
- LeetCode#111 Minimum Depth of Binary Tree
- Leetcode_111_Minimum Depth of Binary Tree
- leetcode 111: Minimum Depth of Binary Tree
- [LeetCode#104, 111]Maximum Depth of Binary Tree, Minimum Depth of Binary Tree