104. 二叉树的最大深度
深度优先搜索
class Solution {
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
/**
* 根节点的高度就是二叉树的最大深度,使用前序遍历求的就是深度,使用后序遍历求的是高度
* 本题可以通过后序遍历求根节点高度来求的二叉树最大深度
* 假设已经求出了根节点左右子树的高度,那根节点高度就等于其加1
*/
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(logn)
*/
广度优先搜索
class Solution {
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
int depth = 0;
queue.add(root);
/**
* 层序遍历
*/
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
if (temp.left != null){
queue.add(temp.left);
}
if (temp.right != null){
queue.add(temp.right);
}
}
depth++;
}
return depth;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/