二叉树相关的三个常见算法题

算法题一

image

// 计算一颗二叉树的所有节点的数量
int BinaryTree_CountNode(Tnode_t *root)
{
    int n1, n2;
    if (NULL == root)
    {
        return 0;
    }
    n1 = BinaryTree_CountNode(root->lchild);
    n2 = BinaryTree_CountNode(root->rchild);
    return n1 + n2 + 1;
}


算法题二

image

// 计算一颗二叉树的所有叶子节点的数量,采用递归的方式实现
int BaniryTree_CountLeafNode(Tnode_t *root)
{
    int n1, n2;
    if (NULL == root)
    {
        return 0;
    }
    else if (root->lchild == NULL && root->rchild == NULL)
    {
        return 1;
    }
    else
    {
        n1 = BaniryTree_CountLeafNode(root->lchild);
        n2 = BaniryTree_CountLeafNode(root->rchild);
    }
    return n1 + n2;
}

算法题三

image

// 计算一颗二叉树的深度,采用递归实现
int BinaryTree_GetDepth(Tnode_t *root)
{
    int n1, n2;
    if (NULL == root)
    {
        return 0;
    }
    else
    {
        n1 = BaniryTree_GetDepth(root->lchild);
        n2 = BaniryTree_GetDepth(root->rchild);
    }

    return (n1 > n2 ? n1 : n2) + 1;
}
posted @ 2024-05-04 23:49  铃是铃铛的铃  阅读(23)  评论(0)    收藏  举报