当前位置:网站首页>【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;
}
};
边栏推荐
- 53. 最小的k个数
- 22-08-01 西安 尚医通(01)跨域配置、Swagger2、R类、统一异常处理和自定义异常、Logback日志
- NAS和私有云盘的区别?1篇文章说清楚
- aws s3 upload file
- Tree Chain Segmentation-
- 罗德里格斯公式(Rodrigues‘ Rotation Formula)推导
- AcWing 1285. 单词 题解(AC自动机)
- 【web】理解 Cookie 和 Session 机制
- 亲身经历过的面试题
- AcWing 1053. Repair DNA problem solution (state machine DP, AC automata)
猜你喜欢
随机推荐
60 Feature Engineering Operations: Using Custom Aggregate Functions【Favorites】
IMU预积分的简单理解
Oracle19c安装图文教程
极大似然估计
OC中new和init的区别
使用docker安装mysql
BioVendor人俱乐部细胞蛋白(CC16)Elisa试剂盒研究领域
欧拉公式的证明
KICAD 小封装拉线卡顿问题 解决方法
【LeetCode】206.反转链表
Curriculum Vitae;CV
Service discovery of kubernetes
【LeetCode】102. Level order traversal of binary tree
790. 数的三次方根
罗德里格斯公式(Rodrigues‘ Rotation Formula)推导
1688以图搜货
Talking about the "horizontal, vertical and vertical" development trend of domestic ERP
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
789. 数的范围
Flask入门学习教程









