本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
104. 二叉树的最大深度
来源:力扣(LeetCode)
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例: 给定二叉树 [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));
}
};
复杂度分析
- 时间复杂度: 每个节点都遍历一次
- 空间复杂度: 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;
}
};
复杂度分析
- 时间复杂度:
- 空间复杂度: