题解 | 二叉树的最大深度

二叉树的最大深度

https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

/**

 * struct TreeNode {

 *  int val;

 *  struct TreeNode *left;

 *  struct TreeNode *right;

 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

 * };

 */

class Solution {

public:

    /**

     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可

 * @param root TreeNode类

     * @return int整型

     */

    int maxDepth(TreeNode* root) {

        if (root == nullptr) {

            return 0;

        }

        int left_depth = maxDepth(root->left);

        int right_depth = maxDepth(root->right);

        return 1 + max(left_depth, right_depth);

    }

};

class Solution {
public:
    int maxDepth(TreeNode* root) {
        //空节点没有深度
        if(root == NULL)
            return 0;
        //队列维护层次后续节点
        queue<TreeNode*> q;
        //根入队
        q.push(root);
        //记录深度
        int res = 0;
        //层次遍历
        while(!q.empty()){
            //记录当前层有多少节点
            int n = q.size();
            //遍历完这一层,再进入下一层
            for(int i = 0; i < n; i++){
                TreeNode* node = q.front();
                q.pop();
                //添加下一层的左右节点
                if(node->left)
                    q.push(node->left);
                if(node->right)
                    q.push(node->right);
            }
            //深度加1
            res++;
        }
        return res;
    }
};

   

DS之二叉树 文章被收录于专栏

二叉树的遍历:前,中,后,层次 二叉树的存储结构:链式,顺序(主要用于完全二叉树) 二叉树的应用场景:二叉搜索树(BST),平衡二叉搜索树(AVL树、红黑树),堆,哈夫曼树,表达式树

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务