LeetCode104:二叉树的最大深度

题目描述

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

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

解题思想

可以使用层序遍历

cpp 复制代码
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;

        queue<TreeNode*> que;
        int depth = 0;
        que.push(root);
        while (!que.empty()) {
            vector<int> vec;
            for (int i = que.size(); i > 0; i--) {
                TreeNode* tmp = que.front();
                que.pop();
                vec.push_back(tmp->val);

                if(tmp->left)  que.push(tmp->left);
                if(tmp->right) que.push(tmp->right);
            }
            
            ++depth;
        }
        return depth;
    }
};

解题思想

使用递归:后序遍历,求高度 。 高度==深度

cpp 复制代码
class Solution  {
public:
    int getDepth(TreeNode* node) {
        if (node == nullptr) return 0;
        //左
        int leftH = getDepth(node->left);
        //右
        int rightH = getDepth(node->right);
        //中
        int height = 1 + max(leftH, rightH);
        return height;
    }

    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};

精简版

cpp 复制代码
class Solution {
public:
    int getDepth(TreeNode* node) {
        if (node == nullptr) return 0;
      
        return 1 + max(getDepth(node->left), getDepth(node->right));
    }

    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};
相关推荐
数据大魔方5 分钟前
【期货量化实战】豆粕期货量化交易策略(Python完整代码)
开发语言·数据库·python·算法·github·程序员创富
memmolo8 分钟前
【3D传感技术系列博客】
算法·计算机视觉·3d
不爱编程爱睡觉8 分钟前
代码随想录算法训练营第四十三天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·leetcode·图论·代码随想录
六毛的毛8 分钟前
冗余连接II
算法
永远都不秃头的程序员(互关)21 分钟前
【K-Means深度探索(二)】K值之谜:肘部法则与轮廓系数,如何选出你的最佳K?
算法·机器学习·kmeans
玄冥剑尊22 分钟前
回溯算法深化 II
算法·回溯算法
Tisfy31 分钟前
LeetCode 3453.分割正方形 I:二分查找
算法·leetcode·二分查找·题解·二分
漫随流水31 分钟前
leetcode算法(101.对称二叉树)
数据结构·算法·leetcode·二叉树
源代码•宸39 分钟前
Golang原理剖析(string面试与分析、slice、slice面试与分析)
后端·算法·面试·golang·扩容·string·slice
派森先生41 分钟前
排序算法-冒泡排序
算法·排序算法