【简单】二叉树的深度 - 2.26

76 阅读1分钟

题目链接:

题解:

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function TreeDepth(pRoot)
{
    // write code here
    if (!pRoot) return 0 // 子树高度为0
    // 不断的递归左右子树,求出子树累计高度最大值
    const left = TreeDepth(pRoot.left)
    const right = TreeDepth(pRoot.right)
    // 树的深度 = 子树高度最大值 + 1
    return Math.max(left, right) + 1 
}

总结:

深度 = 子树高度最大值 + 1

子树高度最大值 = 不断递归左右子树,有子树则加一,不断累加