104. 二叉树的最大深度
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
题目描述见链接内容。
解法1:深度度优先搜索
之前还看过这道题目,结果怎么都想不明白了。利用深度优先搜索,思路是递归调用,先找出边界条件:
if (!root) {
return 0;
}
然后考虑迭代条件,每个节点的最大深度是其左子树和右子树的最大深度加上1
构成的,所以迭代条件就是:
maxDepth = max(leftDepth, rightDepth) + 1;
具体的可以参考官方给出的图解:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pjU1G313-1621223514871)(http://image.oldzhou.cn/FjMnubMXYdzIsCfic1DdWDvC9LSK)]
代码如下:
var maxDepth = function (root) {
if (!root) {
return 0;
}
const leftDepth = maxDepth(root.left),
rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
};
- 时间复杂度:
${O(n)}$
,其中n
为两个二叉树节点的个数 - 空间复杂度:
${O(height)}$
,其中height
为二叉树节点的深度 - 执行用时:80ms,在所有JavaScript提交中击败了97.36%的用户,内存消耗:40.6MB,在所有JavaScript提交中击败了46.55%的用户
解法2:广度优先搜索
利用广度优先搜索,同一个深度的节点会被访问多次,我们没法区分当前节点的深度,所以额外构造一个数据结构,用对象来表示,node
是当前节点,depth
就是当前节点的深度,这样推入队列时把它的深度放到depth
属性上,每次遍历的时候去判断一下当前深度和最大深度的,取二者最大值
var maxDepth = function (root) {
if (!root) {
return 0;
}
let result = 0;
let queue = [{node: root, depth: 1}];
while (queue.length > 0) {
const current = queue.shift();
result = Math.max(result, current.depth);
if (current.node.left) {
queue.push({node: current.node.left, depth: current.depth + 1});
}
if (current.node.right) {
queue.push({node: current.node.right, depth: current.depth + 1});
}
}
return result;
};
- 时间复杂度:
${O(n)}$
,其中n
为两个二叉树节点的个数 - 空间复杂度:
${O(n)}$
,空间复杂度取决于队列存储节点个数,最坏情况会达到${O(n)}$
- 执行用时:96ms,在所有JavaScript提交中击败了50%的用户,内存消耗:41.4MB,在所有JavaScript提交中击败了8%的用户
解法3:广度优先搜索
看了官方题解,还有一种广度优先搜索,就是将一个层级(同一个深度)的节点放到一个数组中,在这个数组遍历完成后,结果加1
,这样原来的队列就变成了一个二维数组,来看代码:
var maxDepth = function (root) {
if (!root) {
return 0;
}
let result = 0;
const queue = [[root]];
while (queue.length > 0) {
const insideQueue = queue.shift();
const temp = [];
while (insideQueue.length > 0) {
const current = insideQueue.shift();
if (current.left) {
temp.push(current.left);
}
if (current.right) {
temp.push(current.right);
}
}
result += 1;
if (temp.length > 0) {
queue.push(temp);
}
}
return result;
};
- 时间复杂度:
${O(n)}$
,其中n
为两个二叉树节点的个数 - 空间复杂度:
${O(n)}$
,空间复杂度取决于队列存储节点个数,最坏情况会达到${O(n)}$
- 执行用时:84ms,在所有JavaScript提交中击败了92%的用户,内存消耗:41.7MB,在所有JavaScript提交中击败了6%的用户