当前位置:网站首页>【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 engineers treat open source

The failure to create a role in Dahua Westward Journey has been solved

极大似然估计

【web】理解 Cookie 和 Session 机制

AI target segmentation capability for fast video cutout without green screen

51. 数字排列

字符串常用方法

国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现

nacos startup error, the database has been configured, stand-alone startup

FOFAHUB使用测试
随机推荐
字符串常用方法
Outsourcing worked for three years, it was abolished...
2022-08-01 安装mysql监控工具phhMyAdmin
MySQL - CRUD operations
IPFS部署及文件上传(golang)
GTK RGB图像绘制
周鸿祎称微软抄袭,窃取360安全模式
使用self和_(下划线)的区别
项目场景 with ERRTYPE = cudaError CUDA failure 999 unknown error
网络层解析——IP协议、地址管理、路由选择
mockjs生成假数据的基本使用
2022 Henan Youth Training League Game (3)
A good book for newcomers to the workplace
记一次gorm事务及调试解决mysql死锁
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
AI target segmentation capability for fast video cutout without green screen
数仓:数仓从ETL到ELT架构的转化以及俩者的区别
JVM调优实战
cadence landscape bindkey
2022年NPDP考完多久出成绩?怎么查询?