当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢

项目场景 with ERRTYPE = cudaError CUDA failure 999 unknown error

搭建zabbix监控及邮件报警(超详细教学)

使用docker安装mysql

yaml

FOFAHUB usage test

Nanoprobes纳米探针丨Nanogold偶联物的特点和应用

Flask 报错:WARNING This is a development server. Do not use it in a production deployment

22-08-01 西安 尚医通(01)跨域配置、Swagger2、R类、统一异常处理和自定义异常、Logback日志

永磁同步电机36问(三)——SVPWM代码实现

KICAD 小封装拉线卡顿问题 解决方法
随机推荐
2022牛客多校四_G M
BioVendor Human Club Cellular Protein (CC16) Elisa Kit Research Fields
极大似然估计
svm.SVC application practice 1--Breast cancer detection
1688API
Nacos源码分析专题(一)-环境准备
国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现
通用客户端架构
Chrome浏览器无法加载已解压的.crx文件的解决办法
2022牛客多校三_F G
网络层解析——IP协议、地址管理、路由选择
Chapter 7 Noise analysis
字典常用方法
最大层内元素和
项目场景 with ERRTYPE = cudaError CUDA failure 999 unknown error
搭建zabbix监控及邮件报警(超详细教学)
使用docker安装mysql
Chapter 10_Index Optimization and Query Optimization
灰度传感器、、、diy原理。。图
IMU预积分的简单理解