Maximum Depth of Binary Tree

来源:互联网 发布:网络销售是什么工作 编辑:程序博客网 时间:2024/05/29 13:09

题目描述:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

思路:

二叉树求最大深度,最直接的方法就是递归。所求二叉树的最大深度等于它左、右子树中深度大的值+1,以此递归,递归边界值是root=NULL。


代码:

int maxDepth(TreeNode *root)
{
    int depth = 1,l=0,r=0;
    if(root==NULL)
        return 0;
    else
    {
        l = maxDepth(root->left);
        r = maxDepth(root->right);
        if(l>r) return depth+l;
        else return depth+r;
    }
}

0 0
原创粉丝点击