【LeetCode】LCR 175.计算二叉树的深度

题目链接:

LCR 175.计算二叉树的深度

题目描述:

思路一(深度优先搜索):

使用深度优先搜索算法进行二叉树后序遍历

复杂度分析:

  • 时间复杂度 O(N):N 为树的节点数量,计算树的深度需要遍历所有节点
  • 空间复杂度 O(N): 最差情况下(当树退化为链表时),递归深度可达到 N
cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int calculateDepth(TreeNode* root) {
        if(root==nullptr) return 0;
        return max(calculateDepth(root->left),calculateDepth(root->right))+1;
    }
};

思路二(广度优先搜索算法):

使用二叉树的层序遍历算法实现

复杂度分析:

  • 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。
  • 空间复杂度 O(N) : 最差情况下(当树平衡时),队列 queue 同时存储 N/2 个节点。
cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int calculateDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        vector<TreeNode*> queue;
        queue.push_back(root);
        int res = 0;

        while(!queue.empty()){
            res++;
            int n = queue.size();
            for(int i =0; i<n; i++){
                TreeNode* node = queue.front(); 
                queue.erase(queue.begin());
                if(node ->left != nullptr) queue.push_back(node ->left);
                if(node ->right != nullptr) queue.push_back(node ->right);
            }
        }

        return res;
    }
};

题解参考:https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof/solutions/159058/mian-shi-ti-55-i-er-cha-shu-de-shen-du-xian-xu-bia/

相关推荐
s:1033 分钟前
【框架】参考 Spring Security 安全框架设计出,轻量化高可扩展的身份认证与授权架构
java·开发语言
道不尽世间的沧桑1 小时前
第17篇:网络请求与Axios集成
开发语言·前端·javascript
久绊A1 小时前
Python 基本语法的详细解释
开发语言·windows·python
StickToForever3 小时前
第4章 信息系统架构(五)
经验分享·笔记·学习·职场和发展
软件黑马王子5 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
闲猫5 小时前
go orm GORM
开发语言·后端·golang
计算机小白一个5 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^6 小时前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
黑不溜秋的6 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
李白同学6 小时前
【C语言】结构体内存对齐问题
c语言·开发语言