代码随想录Day20

LeetCode104.找出二叉树最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例: 给定二叉树 [3,9,20,null,null,15,7]

 

 

 

 返回它的最大深度 3 。

 

深度和高度:

深度是根节点到叶子结点的距离。

高度是叶子节点到根节点的距离。

 

遍历顺序的选取:

高度:左右中(后续遍历)把叶子节点的结果不断返回给根节点。

深度:中左右(前序遍历)从根节点往下遍历。

 

思路:本题求最大深度,其实就是求根节点的高度,根节点的高度就是最大深度。也可以用前序遍历去求。

代码:

复制代码
class solution {
public:
    int getdepth(treenode* node) {
        if (node == NULL) return 0;
        int leftdepth = getdepth(node->left);       //
        int rightdepth = getdepth(node->right);     //
        int depth = 1 + max(leftdepth, rightdepth); //
        return depth;
    }
    int maxdepth(treenode* root) {
        return getdepth(root);
    }
};
复制代码

精简版本:

class solution {
public:
    int maxdepth(treenode* root) {
        if (root == null) return 0;
        return 1 + max(maxdepth(root->left), maxdepth(root->right));
    }
};

前序遍历:真正求深度的基本方法。

复制代码
class solution {
public:
    int result;
    void getdepth(treenode* node, int depth) {
        result = depth > result ? depth : result; //
        if (node->left == NULL && node->right == NULL) return ;
        if (node->left) { //
            getdepth(node->left, depth + 1);
        }
        if (node->right) { //
            getdepth(node->right, depth + 1);
        }
        return ;
    }
    int maxdepth(treenode* root) {
        result = 0;
        if (root == 0) return result;
        getdepth(root, 1);
        return result;
    }
};
复制代码

 

posted @   NobodyHero  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2020-11-09 《java编程思想》---运算符
2020-11-09 java温习---对象
点击右上角即可分享
微信分享提示