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.
先上代码
class Solution {
public:
int run (TreeNode *root) {
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
if (root->left == NULL)
return run(root->right) + 1;
else if (root->right == NULL)
return run(root->left) + 1;
else
return 1 + min(run(root->left), run(root->right));
}
}
解题思路是<a href = "https://zh.wikipedia.org/wiki/%E6%B7%B1%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2">深度优先搜索DFS</a>
严谨一些,我们先把极端的情况先处理一下
- 1 、为空的情况
- 2 、左或者右子树为空的情况
- 3 、我们需要编码处理的情况(递归算出结果)
同理,稍微修改一下我们也可以求出二叉树的最大深度
int maxDepth(TreeNode *root)
{
return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}
😄递归很好使、
网友评论