LeetCode 111. Minimum Depth of Binary Tree
2017-04-09 11:22
309 查看
题目:
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.
思路:
找出最小深度,最小深度是叶节点到根节点的最短路径,如果根节点没有叶节点,返回1,如果根节点只有左节点 ,返回 minDepth(root->left)+1;如果根节点只有右节点,返回minDepth(root->right)+1;如果都有,返回两个中小的。
代码:
**输出结果:**9ms
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.
思路:
找出最小深度,最小深度是叶节点到根节点的最短路径,如果根节点没有叶节点,返回1,如果根节点只有左节点 ,返回 minDepth(root->left)+1;如果根节点只有右节点,返回minDepth(root->right)+1;如果都有,返回两个中小的。
代码:
/** * 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(NULL==root){//如果根节点为NULL,返回0 return 0; } else if(root->left==NULL&&root->right==NULL){//如果根节点没有叶节点,返回1 return 1; } else if(root->left!=NULL&&root->right==NULL){//如果根节点只有左节点 return minDepth(root->left)+1; } else if(root->left==NULL&&root->right!=NULL){//如果根节点只有右节点 return minDepth(root->right)+1; } else{//如果左右节点都有 return min(minDepth(root->left)+1,minDepth(root->right)+1); } } };
**输出结果:**9ms
相关文章推荐
- 【Leetcode】111. Minimum Depth of Binary Tree
- 剑指offer 面试题19:二叉树的镜像(leetcode226. Invert Binary Tree) 题解
- [Leetcode]@python 104. Maximum Depth of Binary Tree
- Leetcode-标签为Tree 111. Minimum Depth of Binary Tree
- LeetCode:Binary Tree Traversal(二叉树遍历非递归)
- Leetcode 111. Minimum Depth of Binary Tree
- LCP104 LeetCode 104. Maximum Depth of Binary Tree
- [Leetcode] Binary tree--112. Path Sum
- [leetcode]@python 111. Minimum Depth of Binary Tree
- LeetCode543. Diameter of Binary Tree
- Leetcode 111,104. Minimum/Maximum Depth of Binary Tree
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode--111. Minimum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode-104. Maximum Depth of Binary Tree
- leetcode 每日一题 104. Maximum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- LeetCode 545. Boundary of Binary Tree
- Leetcode-543. Diameter of Binary Tree