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

相关推荐
愚润求学8 分钟前
【Linux】进程间通信(一):认识管道
linux·运维·服务器·开发语言·c++·笔记
珊瑚里的鱼23 分钟前
【滑动窗口】LeetCode 1658题解 | 将 x 减到 0 的最小操作数
开发语言·c++·笔记·算法·leetcode·stl
落樱弥城27 分钟前
角点特征:从传统算法到深度学习算法演进
人工智能·深度学习·算法
晚秋大魔王36 分钟前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——wget
java·linux·运维·开发语言·华为·harmonyos
heath ceTide39 分钟前
轻量、优雅、高扩展的事件驱动框架——Hibiscus-Signal
java·开发语言
_extraordinary_40 分钟前
Java 常用的Arrays函数
java·开发语言
_extraordinary_43 分钟前
Java 类和对象
java·开发语言
Aliano2171 小时前
TestNGException ClassCastException SAXParserFactoryImpl是Java自带的Xerces解析器——解决办法
java·开发语言·python
共享家95271 小时前
哈希的原理、实现
c++·算法
漫谈网络1 小时前
回调函数应用示例
开发语言·python·回调函数