104.二叉树的最大深度Java
题目描述
给定一颗二叉树,返回该二叉树的最大深度。
输入输出样式
示例1:
给定二叉树 [3,9,20,null,null,15,7]
本题来自LeetCode:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
思路
方法一:深度优先遍历(递归),以当前遍历节点为根节点的二叉树的最大深度为Max(左子树的深度,右子树的深度) + 1. 这就是整个递归的主要思想。
方法二:广度优先遍历,每次将一层的节点加入队列,出列时将队列元素全部出列。记录上述的次数,即为最大深度。
算法分析
方法一:时间复杂度O(n),空间复杂度为O(height)
方法二:时间复杂度O(n),空间复杂度O(n)
求解函数
//方法一:递归
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;
}
//方法二:广度优先遍历
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int ans = 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);
}
size--;
}
ans++;
}
return ans;
}
版权声明:本文为qq_35253136原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。