104. Maximum Depth of Binary Tree Add to List DescriptionHintsSubmissions

本文探讨了如何求解二叉树的最大深度问题,并通过对比两种实现方式,展现了简洁高效的递归解决方案。同时,还提供了计算二叉树最大宽度的额外示例。

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

题目

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


翻译

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

最大深度是从根节点到最远叶节点的最长路径中的节点数。


分析

之前在刷链表的时候有过类似的题,也是递归的方法

思索片刻后写出了如下代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int buildmax(TreeNode* root,int m){
        if(root==NULL)  return m;
        if(root->left==NULL||root->right==NULL)   return m+1;
        m=max(m,buildmax(root->left,m+1),buildmax(root->right,m+1));
        return m;
    } 
    
    int maxDepth(TreeNode* root) {
        int x=buildmax(root,0);
        return x;
    }
};



结果报错, 查询后才知道max min函数不能直接对三个使用,

错误示范:max(a,b,c),

正确示范:max(a,max(b,c)).


然后去答案区学习大神的代码后,男默女泪


Only one line code.

int maxDepth(TreeNode *root)
{
    return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}
后附带大神的最大宽度代码

Calculate the count of the last level.

int maxDepth(TreeNode *root)
{
    if(root == NULL)
        return 0;
    
    int res = 0;
    queue<TreeNode *> q;
    q.push(root);
    while(!q.empty())
    {
        ++ res;
        for(int i = 0, n = q.size(); i < n; ++ i)
        {
            TreeNode *p = q.front();
            q.pop();
            
            if(p -> left != NULL)
                q.push(p -> left);
            if(p -> right != NULL)
                q.push(p -> right);
        }
    }
    
    return res;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值