题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function TreeDepth(pRoot) { // 本题求的是二叉树的最大深度,即二叉树的高度,可以使用后序遍历实现(从下往上的顺序) // 当节点为空,即遍历到叶子节点下个节点时,其高度为0 if(!pRoot) return 0; // 递归求左子树的高度 let leftDepth = TreeDepth(pRoot.left); // 递归求右子树的高度 let rightDepth = TreeDepth(pRoot.right); // 左子树右子树高度的最大值+1即为当前父节点的高度 let depth = Math.max(leftDepth, rightDepth) + 1; return depth; } module.exports = { TreeDepth : TreeDepth };