当前位置:网站首页>【LeetCode】104. Maximum depth of binary tree
【LeetCode】104. Maximum depth of binary tree
2022-08-02 02:46:00 【Crispy~】
题目
给定一个二叉树,找出其最大深度.
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数.
说明: 叶子节点是指没有子节点的节点.
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 .
题解
使用递归
/** * 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 fun(TreeNode* node,int high)
{
if(node==nullptr)
return high;
high++;
return max(fun(node->left,high),fun(node->right,high));
}
int maxDepth(TreeNode* root) {
int high=0;
if(root)
high = fun(root,high);
return high;
}
};
//改进
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==nullptr)
return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
使用广度优先遍历
/** * 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 maxDepth(TreeNode* root) {
if(root==nullptr)
return 0;
int high = 0;
queue<TreeNode*> myqueue;
myqueue.emplace(root);
while(!myqueue.empty())
{
high++;
queue<TreeNode*> temp;
int len = myqueue.size();
while(len>0)
{
len--;
TreeNode* node = myqueue.front();
myqueue.pop();
if(node->left)
myqueue.emplace(node->left);
if(node->right)
myqueue.emplace(node->right);
}
}
return high;
}
};
边栏推荐
- 【LeetCode】104.二叉树的最大深度
- feign调用不通问题,JSON parse error Illegal character ((CTRL-CHAR, code 31)) only regular white space (r
- 一次SQL优化,数据库查询速度提升 60 倍
- Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles
- 通用客户端架构
- PAT甲级打卡-1001-1004
- [Daily LeetCode]——1. The sum of two numbers
- 微信小程序异步回调函数恶梦和解决办法
- 微服务:微智能在软件系统的简述
- AcWing 1285. Word Problem Solving (AC Automata)
猜你喜欢
Lombok
BioVendor人俱乐部细胞蛋白(CC16)Elisa试剂盒研究领域
机器人领域期刊会议汇总
Nanoprobes Polyhistidine (His-) Tag: Recombinant Protein Detection Protocol
很有意思的经历,很有意思的项目--文件夹对比工具
Nacos source code analysis topic (2) - service registration
[Daily LeetCode]——1. The sum of two numbers
esp32经典蓝牙和单片机连接,,,手机蓝牙作为主机
GTK RGB图像绘制
The state status is displayed incorrectly after the openGauss switch
随机推荐
60 Feature Engineering Operations: Using Custom Aggregate Functions【Favorites】
亲身经历过的面试题
qt点云配准软件
局部敏感哈希:如何在常数时间内搜索Embedding最近邻
Swift运行时(派发机制)
永磁同步电机36问(三)——SVPWM代码实现
使用self和_(下划线)的区别
PAT甲级打卡-1001-1004
(一)Redis: 基于 Key-Value 的存储系统
EFCore 反向工程
通用客户端架构
Nanoprobes纳米探针丨Nanogold偶联物的特点和应用
How ReentrantLock works
canal同步Mariadb到Mysql
微服务:微智能在软件系统的简述
Nanoprobes免疫测定丨FluoroNanogold试剂免疫染色方案
yaml
启发式合并、DSU on Tree
项目场景 with ERRTYPE = cudaError CUDA failure 999 unknown error
Curriculum Vitae;CV