加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

minimum-depth-of-binary-tree (搜索)

发布时间:2020-12-14 04:16:12 所属栏目:大数据 来源:网络整理
导读:题意:输出一个二叉树的最小深度。 思路:搜索一下就行了。 注意:搜索的时候,是比较每个子树的左右子树的大小,每个子树的深度要加上根节点! class Solution { public : int run(TreeNode * root) { if (root == NULL) return 0 ; // 空树 if (root-left

题意:输出一个二叉树的最小深度。

思路:搜索一下就行了。

注意:搜索的时候,是比较每个子树的左右子树的大小,每个子树的深度要加上根节点!

class Solution {
public:
    int run(TreeNode *root) {
        if (root == NULL) return 0;        //空树
        if (root->left == NULL) return run(root->right) + 1;
        if (root->right == NULL) return run(root->left) + 1;
        int left = run(root->left);
        int right = run(root->right);
        return (left < right) ? (left+1) : (right+1);
    }
};

?

兄弟题

?maximum-depth-of-binary-tree

题意:输出最大的二叉树的深度

class Solution {
public:
    int maxDepth(TreeNode *root) {
        if (root == NULL)return 0;
        if (root->left == NULL) maxDepth(root->right) + 1;
        if (root->right == NULL)maxDepth(root->left) + 1;
        int left = maxDepth(root->left) + 1;
        int right = maxDepth(root->right) + 1;
        return left > right ? left : right;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读