当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢
随机推荐
2022牛客多校三_F G
20. 用两个栈实现队列
analog IC layout
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
2022 Henan Youth Training League Game (3)
analog IC layout-Parasitic effects
Analysis of the status quo of digital transformation of manufacturing enterprises
qt点云配准软件
Nanoprobes Polyhistidine (His-) Tag: Recombinant Protein Detection Protocol
Unable to log in to the Westward Journey
JVM调优实战
淘宝详情.
Ringtone 1161. Maximum In-Layer Elements and
欧拉公式的证明
Oracle19c安装图文教程
指针数组和数组指针
Oracle数据类型介绍
2022牛客多校四_G M
Service discovery of kubernetes
2022-08-01 Reflection









![[Server data recovery] Data recovery case of server Raid5 array mdisk disk offline](/img/08/d693c7e2fff8343b55ff3c1f9317c6.jpg)