【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/

相关推荐
love is sour1 天前
聚类(Clustering)详解:让机器自己发现数据结构
算法·支持向量机·聚类
烟袅1 天前
LeetCode 142:环形链表 II —— 快慢指针定位环的起点(JavaScript)
前端·javascript·算法
CoovallyAIHub1 天前
OCR战场再起风云:LightOnOCR-1B凭什么比DeepSeekOCR快1.7倍?(附演示开源地址)
深度学习·算法·计算机视觉
j_xxx404_1 天前
C++ STL:list|了解list|相关接口|相关操作
开发语言·c++
kyle~1 天前
机器视觉---Intel RealSense SDK 2.0 开发流程
运维·c++·windows·深度相机·intel realsense
海琴烟Sunshine1 天前
leetcode 190. 颠倒二进制位 python
python·算法·leetcode
脏脏a1 天前
类与对象(上):面向过程到面向对象的跨越,类的定义、封装与 this 指针等核心概念深度剖析
开发语言·c++
Xの哲學1 天前
Linux eMMC子系统深度解析:从硬件协议到内核实现
linux·网络·算法·架构·边缘计算
AI柠檬1 天前
C语言基于MPI并行计算矩阵的乘法
c语言·c++·算法
lin__ying1 天前
机器学习-聚类
算法·机器学习