求二叉树的深度

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次通过的结点(含根、叶结点)造成树的一条路径,最长路径的长度为树的深度。node

地址:https://www.nowcoder.com/prac...this

递归

思路:递归求左子树和右子树深度,而后比较,最终返回最大值加1。code

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function TreeDepth(node) {
    if(node == null) {
        return 0;
    }
    let left = TreeDepth(node.left);
    let right = TreeDepth(node.right);
    return left > right ? left+1 : right+1; // 不要写成left++,  right++
}
相关文章
相关标签/搜索