当前位置:网站首页>【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;
}
};
边栏推荐
- 架构:微服务网关(SIA-Gateway)简介
- ApiFox 基本使用教程(浅尝辄止,非广)
- The state status is displayed incorrectly after the openGauss switch
- 架构:应用架构的演进以及微服务架构的落地实践
- 架构:分布式任务调度系统(SIA-Task)简介
- 亲身经历过的面试题
- Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
- 搭建zabbix监控及邮件报警(超详细教学)
- FOFAHUB usage test
- 【LeetCode】145.二叉树的后序遍历
猜你喜欢
随机推荐
剑指 Offer 14- I. 剪绳子
20. 用两个栈实现队列
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
Tree Chain Segmentation-
有人知道HTML怎么到MYSQL数据库吗? (NODEJS)
忽晴忽雨
The state status is displayed incorrectly after the openGauss switch
Chapter 7 Noise analysis
aws s3 upload file
微服务:微智能在软件系统的简述
接口测试神器Apifox究竟有多香?
IPFS deployment and file upload (golang)
OC中成员变量,实例变量和属性之间的区别和联系
Chrome浏览器无法加载已解压的.crx文件的解决办法
analog IC layout-Environmental noise
AcWing 1285. 单词 题解(AC自动机)
四元数、罗德里格斯公式、欧拉角、旋转矩阵推导和资料
NIO's Sword
JS中获取对象数据类型的键值对的键与值
svm.SVC应用实践1--乳腺癌检测









