题解 | #二叉树的最大深度#

二叉树的最大深度

https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73

/**
 * 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 search(TreeNode* cur){
    //     if(cur==nullptr)return 0;
    //     int left=search(cur->left);
    //     int right=search(cur->right);
    //     return max(left,right)+1;
        
    // }
    int maxDepth(TreeNode* root) {
    //     // write code here
    //     int result=search(root);
    //     return result;
    // }
    queue<TreeNode*>que;
    if(root==nullptr)return 0;
    que.push(root);
    int count=0;
    while(!que.empty()){
        int size=que.size();
        for(int i=0;i<size;i++){
        TreeNode* node=que.front();
        que.pop();
        if(node->left)que.push(node->left);
        if(node->right)que.push(node->right);
        }
        count++;
    }
    return count;

    
    }
};

层序遍历的解题思路

建立队列

用while+for循环把每一层节点都推入队列里

全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 14:50
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-23 17:32
那如果是字节外包呢?据我所知工牌无区别&nbsp;可以晒出去装X的那种
秋盈丶:残酷的是,都一样,管你是不是字节,不过我是很反对这种的,本是同根生,市场行情决定了用工的模式会有很多外包,分层只是单纯为了筛选
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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