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

相关推荐
视觉人机器视觉3 分钟前
Visual Studio2022和C++opencv的配置保姆级教程
c++·opencv·visual studio
liulilittle5 分钟前
C++ i386/AMD64平台汇编指令对齐长度获取实现
c语言·开发语言·汇编·c++
Wilber的技术分享21 分钟前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
Tanecious.34 分钟前
LeetCode 876. 链表的中间结点
算法·leetcode·链表
Thomas_YXQ38 分钟前
Unity URP法线贴图实现教程
开发语言·unity·性能优化·游戏引擎·unity3d·贴图·单一职责原则
Wo3Shi4七43 分钟前
哈希冲突
数据结构·算法·go
Zz_waiting.1 小时前
Javaweb - 10.4 ServletConfig 和 ServletContext
java·开发语言·前端·servlet·servletconfig·servletcontext·域对象
呆呆的小鳄鱼1 小时前
cin,cin.get()等异同点[面试题系列]
java·算法·面试
Touper.1 小时前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun0077001 小时前
std::forward作用
开发语言·c++·算法