当前位置:网站首页>leetcode:104. 二叉树的最大深度
leetcode:104. 二叉树的最大深度
2022-06-30 22:06:00 【uncle_ll】
104. 二叉树的最大深度
来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/maximum-depth-of-binary-tree/
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
解法
- 递归:从根节点开始,如果该节点为空,则返回0;如果不为0,递归调用查找左右子树的深度,最终结果为根节点的1层+ max(left, right)
- bfs循环: bfs层序遍历即可知道层数是多少,使用队列存储每层的节点,基于每层的节点数进行循环遍历入队列,每层遍历完毕后高度+1
代码实现
递归
python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
c++实现
/** * 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;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
复杂度分析
- 时间复杂度: O ( N ) O(N) O(N) 每个节点都遍历一次
- 空间复杂度: O ( h e i g h t ) O(height) O(height) height是二叉树的高度,递归需要栈空间,栈空间取决于递归的深度
BFS循环
python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# bfs
queue = [root]
height = 0
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
height += 1
return height
c++实现
/** * 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;
deque<TreeNode*> dq;
dq.push_back(root);
int height = 0;
while (dq.size() != 0) {
int tmp_size = dq.size();
for (int i=0; i<tmp_size; i++) {
TreeNode * node = dq.front();
dq.pop_front();
if (node->left != nullptr)
dq.push_back(node->left);
if (node->right != nullptr)
dq.push_back(node->right);
}
height++;
}
return height;
}
};
复杂度分析
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( N ) O(N) O(N)
边栏推荐
- I want to know who I need to know to open a stock account? In addition, is it safe to open a mobile account?
- [career planning for Digital IC graduates] Chap.1 overview of IC industry chain and summary of representative enterprises
- [BSP video tutorial] BSP video tutorial issue 19: AES encryption practice of single chip bootloader, including all open source codes of upper and lower computers (June 26, 2022)
- JD and Tencent renewed the three-year strategic cooperation agreement; The starting salary rose to 260000 yuan, and Samsung sk of South Korea scrambled for a raise to retain semiconductor talents; Fir
- 微服務鏈路風險分析
- The Three Musketeers: One for All!
- 实现多方数据安全共享,解决普惠金融信息不对称难题
- PostgreSQL存储结构浅析
- [micro service ~nacos] configuration center of Nacos
- ML&DL:机器学习和深度学习中超参数优化的简介、评估指标、过拟合现象、常用的调参优化方法之详细攻略
猜你喜欢

Is there a shortage? No need to download the free online resources! 2022 favorites must have it!

【BSP视频教程】BSP视频教程第19期:单片机BootLoader的AES加密实战,含上位机和下位机代码全开源(2022-06-26)

电脑设备管理器在哪里可以找到

dba

5G 在智慧医疗中的需求

盘点华为云GaussDB(for Redis)六大秒级能力
![Flip the linked list ii[three ways to flip the linked list +dummyhead/ head insertion / tail insertion]](/img/a8/6472e2051a295f5e42a88d64199517.png)
Flip the linked list ii[three ways to flip the linked list +dummyhead/ head insertion / tail insertion]

Rethink healthy diet based on intestinal microbiome

Introduce an online platform for multi omics integration and network visual analysis
Notes [introduction to JUC package and future]
随机推荐
实现多方数据安全共享,解决普惠金融信息不对称难题
Zhoushaojian, rare
dba
Flip the linked list ii[three ways to flip the linked list +dummyhead/ head insertion / tail insertion]
顺祝老吴的聚会
What is the experience of pairing with AI? Pilot vs alphacode, Codex, gpt-3
从PG15 XID64再次跳票说起
【MySQL入门】第一话 · 初入“数据库”大陆
HDFS centralized cache management
Some memory problems summarized
Installing jupyter notebook under Anaconda
Graduation project
Pytorch quantitative practice (2)
B_ QuRT_ User_ Guide(31)
Akk bacteria - the next generation of beneficial bacteria
将Nagios监控信息存入MySQL
Pytorch quantitative perception training (qat) steps
How does win11 optimize services? Win11 method of optimizing service
5g demand in smart medicine
腾讯3年,功能测试进阶自动化测试,送给在手工测试中迷茫的你