当前位置:网站首页>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)
边栏推荐
- 《安富莱嵌入式周报》第271期:2022.06.20--2022.06.26
- RP prototype resource sharing - shopping app
- Introduction to go web programming: a probe into the excellent test library gocovey
- Turn: win others' follow with practical actions
- How to use data sets in machine learning?
- Nansen复盘加密巨头自救:如何阻止百亿多米诺倾塌
- B_ QuRT_ User_ Guide(34)
- The Three Musketeers: One for All!
- 艾芬医生事件解析
- Installing jupyter notebook under Anaconda
猜你喜欢
Analysis of PostgreSQL storage structure
京东与腾讯续签三年战略合作协议;起薪涨至26万元,韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条
阿婆做的臭豆腐
Web APIs comprehensive case -tab column switching - dark horse programmer
总结的一些内存问题
Tencent has been conducting advanced automated functional testing for 3 years. It is a gift to you who are confused in manual testing
About, Qianxin detects code vulnerabilities and XSS series solves them
Windbg调试工具介绍
Nansen double disk encryption giant self rescue: how to prevent the collapse of billions of dominoes
Ten of the most heart piercing tests / programmer jokes, read the vast crowd, how to find?
随机推荐
How to develop the exchange system? Mature technology case of digital currency exchange system development
Turn: win others' follow with practical actions
顺祝老吴的聚会
Akk bacteria - the next generation of beneficial bacteria
Stinky tofu made by Grandma
Is Wu Enda's machine learning suitable for entry?
2022中国国潮发展新动向
京东与腾讯续签三年战略合作协议;起薪涨至26万元,韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条
Error reporting: internal error XFS_ WANT_ CORRUPTED_ GOTO at line 1635 of file fs/xfs/libxfs/xfs_ alloc. c.
从PG15 XID64再次跳票说起
Apache server OpenSSL upgrade
Troubleshooting the problem of pytorch geometric torch scatter and torch spark installation errors
1-17 express Middleware
Uniapp rich text editor
将Nagios监控信息存入MySQL
JVM Part 21 of interview with big companies Q & A
B_ QuRT_ User_ Guide(33)
HDFS centralized cache management
Graduation project
Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing