求二叉树的深度

作者: 黎贝卡beka | 来源:发表于2018-08-23 18:50 被阅读2次

    题目描述

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

    地址:https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    递归

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

    /* 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++
    }
    

    相关文章

      网友评论

        本文标题:求二叉树的深度

        本文链接:https://www.haomeiwen.com/subject/glvmiftx.html