美文网首页
104.Maximum Depth of Binary Tree

104.Maximum Depth of Binary Tree

作者: 花落花开花满天 | 来源:发表于2018-11-10 14:50 被阅读0次

找树的最深层数,从叶子节点向上累加,得到最深层数。

使用了两种判定方法,方法1是判定节点为空节点再回滚,时间是8ms;另一种是当节点存在空子节点时便开始判断,避免进入空节点,因此可节约一半的时间。

代码1:

int maxDepth(TreeNode* root) {

        if(root==NULL)

        return 0;

    else

    {

        int l=maxDepth(root->left);

        int r=maxDepth(root->right);

        return l>=r?l+1:r+1;

    }

    }

代码2:

bool maxDepth(TreeNode* root) {

    if(root==NULL)

        return 0;

    if(root->left==NULL && root->right==NULL)

    {

        return 1;

    }

    else if(root->left==NULL || root->right==NULL)

    {

        if(root->left==NULL)

            return maxDepth(root->right)+1;

        if(root->right==NULL)

        return maxDepth(root->left)+1;

    }

    else

    {

        int l=maxDepth(root->left);

        int r=maxDepth(root->right);

        return l>=r?l+1:r+1;

    }

    return 0;

}

相关文章

网友评论

      本文标题:104.Maximum Depth of Binary Tree

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