Maximum Depth of Binary Tree--二叉树的深度

本文深入解析了如何通过递归算法计算二叉树的深度,并提供了相应的代码实现。文章从理论出发,逐步引导读者理解算法逻辑,最终通过实例展示代码实现过程及执行结果。

摘要生成于 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 binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
    }
};


晓东分析:

这其实是一个很基础的题目,稍微有点基础的同学应该都写过,所以也就不需要详细说明什么。这种题目使用递归的算法是最简单的,思路就是先求出左节点为根节点的二叉树的深度,再求出右节点为根节点的二叉树深度,然后看这两者谁大,大的那个加上1就是原来的二叉树的深度。

代码实现:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int left_depth = 0;
        int right_depth = 0;
        if(NULL == root) return 0;
        left_depth = maxDepth(root->left);
        right_depth = maxDepth(root->right);
        return left_depth > right_depth ? left_depth + 1 : right_depth + 1;
            
    }
};


执行结果:

38 / 38test cases passed.
Status:
Accepted
Runtime: 44 ms

执行时间还是可以接收的。

 

希望大家有更好的算法能够提出来,不甚感谢。

 

若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值