LeetCode-104. Maximum Depth of Binary Tree

本文介绍了求解二叉树最大深度的两种方法:递归深度优先搜索(DFS)及非递归广度优先搜索(BFS)。递归方法通过比较左右子树的最大深度来确定整棵树的深度;非递归方法利用队列实现层序遍历来计算层数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 题目

Maximum Depth of Binary Tree

给定一个二叉树,找到它的最大深度。

2. 分析

最大深度是沿最长路径的节点数,从根节点向下到最远的叶节点。
1:递归,采用DFS返回左子树与右子树中较大的深度加1即可
时间复杂度 O(n),空间复杂度 O(logn)
2:非递归,采用BFS进行层序遍历,总层数即为二叉树最大深度
使用其他遍历同样需要O(n)的复杂度,但层序遍历更直观

3. 代码

1)递归

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;

        int left = maxDepth(root->left);
        int right = maxDepth(root->right);

        return max(left, right) + 1;
        // return max(maxDepth(root->left), maxDepth(root->right)) + 1; 
    }
};

若是写成

if(maxDepth(root->left) > maxDepth(root->right))
    return maxDepth(root->left) + 1;
else
    return maxDepth(root->right) + 1;

则会因maxDepth调用次数过多导致Submission Result: Time Limit Exceeded

2)非递归

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;

        queue<TreeNode*> q;
        q.push(root);
        int level = 0;

        while(!q.empty())
        {
            ++level;

            int len = q.size();
            for(int i = 0; i < len; ++i)
            {
                TreeNode *node = q.front();
                q.pop();

                if(node->left)
                    q.push(node->left);
                if(node->right)
                    q.push(node->right);
            }
        }

        return level;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值