题目: 给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。 题目链接
我的JavaScript解法
- 深度优先搜索1
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if(root == null) return 0;
const maxLeft = maxDepth(root.left);
const maxRight = maxDepth(root.right);
return 1 + Math.max(maxLeft, maxRight);
};
- 深度优先搜索2
var maxDepth = function(root) {
let maxDepth = Number.MIN_SAFE_INTEGER;
const dfs = (root, depth) => {
if(root == null) return depth;
if(root.left == null && root.right == null) {
maxDepth = Math.max(depth + 1, maxDepth);
return maxDepth;
}
dfs(root.left, depth + 1);
dfs(root.right, depth + 1);
}
dfs(root, 0);
return maxDepth === Number.MIN_SAFE_INTEGER ? 0 : maxDepth;
}
解析: 遍历二叉树
- 时间复杂度:
- 空间复杂度: