力扣-104. 二叉树的最大深度

1.题目介绍

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

提示:

  • 树中节点的数量在 [0,104] 区间内。
  • 100<=Node.val<=100

2.题解

2.1 方法一:深度优先搜索DFS

思路

DFS递归, 考虑结束条件是空指针
且对于一个根节点对应的子树最大深度 = 左/右子树中的较大深度 + 1

代码

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

2.2 用栈消除递归(迭代)

思路

用栈记录结点和其所处深度

代码

#include <stack>
#include <utility> // for std::pair

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;

        std::stack<std::pair<TreeNode*, int>> stack;
        stack.push({root, 1});
        int max_depth = 0;

        while (!stack.empty()) {
            auto [node, depth] = stack.top();
            stack.pop();
            if (node != nullptr) {
                max_depth = std::max(max_depth, depth);
                stack.push({node->left, depth + 1});
                stack.push({node->right, depth + 1});
            }
        }

        return max_depth;
    }
};

2.3 方法二:广度优先搜索BFS

思路

用队列存储一层所有节点的信息,在进入下一层时,将其一一出队,检测是否有左右子树,同时使用标记变量记录层数。
若有,说明下一层存在,同时将该节点入队,作为下一层检测时的树节点;
若无,说明下一层不存在,当前层数为最大层数,退出循环。

代码

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        queue<TreeNode*> Q;
        Q.push(root);
        int ans = 0;
        while (!Q.empty()){
            int sz = Q.size();
            while(sz > 0){
                TreeNode *temp = Q.front(); Q.pop();
                if (temp->left) Q.push(temp->left);
                if (temp->right) Q.push(temp->right);
                sz--;
            }
            ans++;
        } 
        return ans;
    }
};
posted @   DawnTraveler  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示