当前位置:网站首页>【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】83.删除排序链表中的重复元素
FOFAHUB usage test
面对职场“毕业”,PM&PMO应该如何从容的应对?如何跳槽能够大幅度升职加薪?
【LeetCode】1374. 生成每种字符都是奇数个的字符串
【LeetCode】102. Level order traversal of binary tree
【web】Understanding Cookie and Session Mechanism
Flask入门学习教程
剑指 Offer 14- I. 剪绳子
Flask之路由(app.route)详解
搭建zabbix监控及邮件报警(超详细教学)
通用客户端架构
Nanoprobes Polyhistidine (His-) Tag: Recombinant Protein Detection Protocol
永磁同步电机36问(二)——机械量与电物理量如何转化?
ReentrantLock工作原理
Remember a gorm transaction and debug to solve mysql deadlock
* 比较版本号
ApiFox 基本使用教程(浅尝辄止,非广)
局部敏感哈希:如何在常数时间内搜索Embedding最近邻
指针数组和数组指针
【web】理解 Cookie 和 Session 机制









