1. 程式人生 > >二叉樹的深度、葉子節點數

二叉樹的深度、葉子節點數

二叉樹的深度 遞迴

int DepthOfTree(Node* root)
{
    if(root)
    {
        return DepthOfTree(root->Left)>DepthOfTree(root->Right)?DepthOfTree(root->Left)+1:DepthOfTree(root->Right)+1;
    }
    if( root == NULL )
    {
        return 0;
    }
}

二叉樹葉子節點數 遞迴

int Leafnum(Node* root)
{
    if(root == NULL)
    {
        return 0;
    }
    else if(  (root->Left == NULL) && (root->Right == NULL) )
    {
        return 1;
    }
    else
    {
        return  (Leafnum(root->Left) + Leafnum(root->Right)) ;
    }
}