获取二叉树的最大深度思路:
最好的方法是通过遍历来解决,后续可以改版为通过while循环来解决遍历容易引起的内存泄漏。

思路:

从根节点出发,depth + 1,遍历根结点的左节点,depth + 1,直到最后一个左节点不存在,此时遍历最后一个左节点下的右节点,depth + 1,直到最后一个右节点不存在,递归时永远保持递归变量 depth 的最大值,这样可以一直遍历完所有节点,此时的 depth 即为二叉树的最大深度。

代码实现(js版本)

声明二叉树为一个 object ,里面含有 left(左节点) 和 right(右节点) 属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
const getMaxDepthFromBinaryTree = (currentBinaryTreeNode) => {
let depth = 0

if(! currentBinaryTreeNode) return 0
let leftNode = getMaxDepthFromBinaryTree(currentBinaryTreeNode.leftNode)
let rightNode = getMaxDepthFromBinaryTree(currentBinaryTreeNode.rightNode)
if(leftNode > rightNode){
depth = leftNode + 1
}else {
depth = rightNode + 1
}
return depth
}