• 思想:

递归实现

 图示为举例二叉树进行思路解释

二叉树中结点的个数:只要能计算出A左子树的个数+A右子树的个数+1

左子树个数:以B为结点的左子树个数+右子树个数+1

右子树个数:以C为结点的左子树个数+右子树个数+1

 . . . .(每颗子树都能再细分拆为子树)

直到待访问的子树为空树

  • 代码实现:

typedef struct node
{
    char value;//当前节点值
    struct node* left;//指向当前节点左孩子指针
    struct node* right;//指向当前节点右孩子指针
}Node;

typedef struct tree
{
    Node* root;
}Tree;

void InitTree(Tree* t)
{
    t->root = NULL;
}

//先序遍历创建二叉树
Node* Create(const char*& str) //因为要修改字符串就加了引用&
{
    if (*str == '*')
        return NULL;
    else
    {
        Node* newnode = (Node*)malloc(sizeof(Node));
        if (newnode != NULL)
        {
            newnode->value = *str;
            newnode->left = Create(++str);
            newnode->right = Create(++str);
            return newnode;
        }
    }
}

//计算以root为根的二叉树的结点个数
int Size(Node* root)
{
    if (root == NULL)
        return 0;
    else
        return Size(root->left) + Size(root->right) + 1;
}
int main()
{
    Tree t;
    InitTree(&t);
    const char* str = "ABDG**HI****CE*J**F**";
    t.root = Create(str);
    printf("size=%d\n",Size(t.root));
}

                创建的二叉树如下图所示,创建思路:创建二叉树

  • 运行结果:

 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐