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

相关推荐
爱吃烤鸡翅的酸菜鱼6 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
呆呆的小鳄鱼24 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香25 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely26 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_071226 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_42 分钟前
cf1925B&C
数据结构·算法
心情好的小球藻43 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先