# 二叉树的最大深度

# 题目描述

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

# 解题思路

  1. 深度遍历二叉树,比较出左子树的最大深度和右子树的最大深度
  2. 二叉树的最大深度为上面比较的结果 + 1.

# coding

解法一: 较为复杂

实现上和 二叉搜索树的第k个节点有点类似:

class Tree {
    constructor(value = 0, left = null, right = null) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}
function getMaxDeep(tree) {
    if (!tree) return 0;
    let deep = 0, // 定义一个路径的深度
        maxDeep = 0; // 定义最大的深度
    function _getMaxDeep(node) {
        if (!node) return; // 若是没有节点则直接返回
        deep++;
        let isLeaf = !node.left && !node.right; // 判断是否是叶子节点
        if (isLeaf && deep > maxDeep) { // 若是叶子节点且当前路径的深度大于最大的深度
            maxDeep = deep;
        }
        if (node.left) { // 若是有左子树节点则遍历
            _getMaxDeep(node.left)
        }
        if (node.right) {
            _getMaxDeep(node.right)
        }
        deep--; // 遍历完之后将deep重置
    }
    _getMaxDeep(tree);
    return maxDeep;
}

const tree = new Tree(1, new Tree(2, new Tree(4), new Tree(6, new Tree(7))), new Tree(3, null, new Tree(5)));
console.log(getMaxDeep(tree))
// 4

解法二:简单明了

function treeDepth (node) {
    return !node ? 0 : Math.max(treeDepth(node.left), treeDepth(node.right)) + 1;
}
const tree = new Tree(1, new Tree(2, new Tree(4), new Tree(6, new Tree(7))), new Tree(3, null, new Tree(5)));
console.log(treeDepth(tree))
// 4
阅读全文