给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
感谢数据结构和算法的详细解法,传送门递归,BFS,DFS的3种解决方式。
class Solution {
//最大深度
int max = 0;
//遍历到的节点的深度
int depth = 0;
public int maxDepth(TreeNode root) {
// return maxDepthI(root);
// return maxDepthII(root);
// return maxDepthIII(root);
return maxDepthIIII(root);
}
//方法四:DFS遍历,使用两个栈,一个记录节点,一个记录节点所在的层数
//stack中每个节点在level中都会有一个值对应,并且stack和level同时入栈和出栈
//时间复杂度O(N),空间复杂度O(N)
private int maxDepthIIII(TreeNode root) {
if (root == null) {
return 0;
}
int max = 0;
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> level = new Stack<>();
stack.push(root);
level.push(1);
while (!stack.isEmpty()) {
int temp = level.pop();
TreeNode node = stack.pop();
max = Math.max(max, temp);
if (node.right != null) {
stack.push(node.right);
level.push(temp + 1);
}
if (node.left != null) {
stack.push(node.left);
level.push(temp + 1);
}
}
return max;
}
//方法三:BFS遍历,定义变量记录二叉树的层数
//时间复杂度O(N),空间复杂度O(N)
private int maxDepthIII(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int max = 0;
while (!queue.isEmpty()) {
//队列存放的是当前层的所有节点
int size = queue.size();
while (size-- > 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
max++;
}
return max;
}
//方法二:二叉树的遍历框架
private int maxDepthII(TreeNode root) {
traverse(root);
return max;
}
//depth是当前遍历到的节点的深度,所以需要在前序位置加1,后序位置减1
private void traverse(TreeNode root) {
if (root == null) {
//到达叶子结点,更新最大深度
max = Math.max(max, depth);
return;
}
depth++;
traverse(root.left);
traverse(root.right);
depth--;
}
//方法一:递归,时间和空间复杂度O(N)
private int maxDepthI(TreeNode root) {
if (root == null) {
return 0;
}
int leftMax = maxDepth(root.left);
int rightMax = maxDepth(root.right);
return Math.max(leftMax, rightMax) + 1;
}
}