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

二叉树的最大深度

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循环把每一层节点都推入队列里

全部评论

相关推荐

Beeee0927:正确的建议
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务