当前位置:网站首页>【LeetCode】104.二叉树的最大深度
【LeetCode】104.二叉树的最大深度
2022-08-02 02:40:00 【酥酥~】
题目
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [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;
}
};
边栏推荐
猜你喜欢
How to adjust the cross cursor too small, CAD dream drawing calculation skills
记一次gorm事务及调试解决mysql死锁
Pinduoduo leverages the consumer expo to promote the upgrading of domestic agricultural products brands and keep pace with international high-quality agricultural products
IMU预积分的简单理解
第11章_数据库的设计规范
analog IC layout
面对职场“毕业”,PM&PMO应该如何从容的应对?如何跳槽能够大幅度升职加薪?
Electronic Manufacturing Warehouse Barcode Management System Solution
GTK RGB图像绘制
十字光标太小怎么调节、CAD梦想画图算量技巧
随机推荐
周鸿祎称微软抄袭,窃取360安全模式
简单的页面跳转活动
2022-08-01 mysql/stoonedb慢SQL-Q18分析
【web】理解 Cookie 和 Session 机制
aws s3上传文件
数仓:为什么说 ETL 的未来不是 ELT,而是 EL (T)
ApiFox 基本使用教程(浅尝辄止,非广)
工程师如何对待开源
OC中成员变量,实例变量和属性之间的区别和联系
60 Feature Engineering Operations: Using Custom Aggregate Functions【Favorites】
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
PHP live source code to achieve simple barrage effect related code
最大层内元素和
TKU remembers a single-point QPS optimization (I wish ITEYE is finally back)
KICAD 小封装拉线卡顿问题 解决方法
Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles
2022-07-30 mysql8 executes slow SQL-Q17 analysis
2022.8.1-----leetcode.1374
Curriculum Vitae;CV
53. 最小的k个数