LeetCode-二叉树最小深度

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;
}

😄递归很好使、

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容