给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
简单
https://leetcode.cn/problems/maximum-depth-of-binary-tree/
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:3
示例 2:
输入:root = [1,null,2]
输出:2
[0, 10^4]
范围内。-100 <= Node.val <= 100
二叉树的最大深度是一个经典的树问题,可以通过多种方法解决。
最直观的方法是使用递归。二叉树的最大深度等于左子树和右子树的最大深度中的较大值加1(当前节点的深度)。
递归的终止条件是当前节点为空,此时深度为0。
我们也可以使用广度优先搜索(BFS)来解决这个问题。通过层序遍历二叉树,记录遍历的层数,最终层数就是树的最大深度。
除了递归实现深度优先搜索外,我们还可以使用栈来模拟递归过程,实现迭代版本的深度优先搜索。
size
,这代表当前层的节点数量。size
个节点出队,并将它们的非空子节点入队。以示例 1 为例,root = [3,9,20,null,null,15,7]
:
递归(DFS)方法:
迭代(BFS)方法:
迭代(DFS)方法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
// 方法一:递归(DFS)
public int MaxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = MaxDepth(root.left);
int rightDepth = MaxDepth(root.right);
return Math.Max(leftDepth, rightDepth) + 1;
}
// 方法二:迭代(BFS)
public int MaxDepthBFS(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int depth = 0;
while (queue.Count > 0) {
depth++;
int levelSize = queue.Count;
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.Dequeue();
if (node.left != null) {
queue.Enqueue(node.left);
}
if (node.right != null) {
queue.Enqueue(node.right);
}
}
}
return depth;
}
// 方法三:迭代(DFS)
public int MaxDepthDFSIterative(TreeNode root) {
if (root == null) {
return 0;
}
Stack<(TreeNode node, int depth)> stack = new Stack<(TreeNode, int)>();
stack.Push((root, 1));
int maxDepth = 0;
while (stack.Count > 0) {
var (node, depth) = stack.Pop();
maxDepth = Math.Max(maxDepth, depth);
if (node.right != null) {
stack.Push((node.right, depth + 1));
}
if (node.left != null) {
stack.Push((node.left, depth + 1));
}
}
return maxDepth;
}
}
# 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:
# 方法一:递归(DFS)
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1
# 方法二:迭代(BFS)
def maxDepthBFS(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
from collections import deque
queue = deque([root])
depth = 0
while queue:
depth += 1
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
# 方法三:迭代(DFS)
def maxDepthDFSIterative(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
stack = [(root, 1)]
max_depth = 0
while stack:
node, depth = stack.pop()
max_depth = max(max_depth, depth)
if node.right:
stack.append((node.right, depth + 1))
if node.left:
stack.append((node.left, depth + 1))
return max_depth
/**
* 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:
// 方法一:递归(DFS)
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
// 方法二:迭代(BFS)
int maxDepthBFS(TreeNode* root) {
if (root == nullptr) {
return 0;
}
queue<TreeNode*> q;
q.push(root);
int depth = 0;
while (!q.empty()) {
depth++;
int levelSize = q.size();
for (int i = 0; i < levelSize; i++) {
TreeNode* node = q.front();
q.pop();
if (node->left != nullptr) {
q.push(node->left);
}
if (node->right != nullptr) {
q.push(node->right);
}
}
}
return depth;
}
// 方法三:迭代(DFS)
int maxDepthDFSIterative(TreeNode* root) {
if (root == nullptr) {
return 0;
}
stack<pair<TreeNode*, int>> stk;
stk.push({root, 1});
int maxDepth = 0;
while (!stk.empty()) {
auto [node, depth] = stk.top();
stk.pop();
maxDepth = max(maxDepth, depth);
if (node->right != nullptr) {
stk.push({node->right, depth + 1});
}
if (node->left != nullptr) {
stk.push({node->left, depth + 1});
}
}
return maxDepth;
}
};
方法 | 时间复杂度 | 空间复杂度 | 优点 | 缺点 |
---|---|---|---|---|
递归(DFS) | O(n) | O(h),h为树的高度 | 实现简单,代码简洁 | 对于深度很大的树,可能导致栈溢出 |
迭代(BFS) | O(n) | O(n) | 避免了递归可能导致的栈溢出问题 | 需要使用队列,空间复杂度较高 |
迭代(DFS) | O(n) | O(n) | 避免了递归可能导致的栈溢出问题 | 实现稍复杂,需要使用栈和额外的深度信息 |