#include <stdio.h>
#include <stdlib.h>

//二叉链节点类型
typedef struct Node
{
    int data;
    struct Node* Lchild, * Rchild;
}TreeNode;

//初始
void treeNodeInit(int level, TreeNode* treeNode)
{
    if (level > 0)
    {
        treeNode->Lchild = (TreeNode*)malloc(sizeof(TreeNode));
        treeNode->Lchild->data = level;
        treeNode->Lchild->Lchild = NULL;
        treeNode->Lchild->Rchild = NULL;
        treeNode->Rchild = (TreeNode*)malloc(sizeof(TreeNode));
        treeNode->Rchild->data = level;
        treeNode->Rchild->Lchild = NULL;
        treeNode->Rchild->Rchild = NULL;
        treeNodeInit(level - 1, treeNode->Lchild);
        treeNodeInit(level - 1, treeNode->Rchild);
    }
}

void displayTreeNode(TreeNode* treeNode)
{
    if (treeNode != NULL)
    {
        printf("%d  ", treeNode->data);
        displayTreeNode(treeNode->Lchild);
        displayTreeNode(treeNode->Rchild);
    }
}

//递归求二叉链和
int sumTreeNode(TreeNode* treeNode)
{
    if (treeNode->Lchild == NULL && treeNode->Rchild == NULL)
    {
        return treeNode->data;
    }
    else
    {
        return sumTreeNode(treeNode->Lchild) + sumTreeNode(treeNode->Rchild) + treeNode->data;
    }
}

int main()
{
    TreeNode* treeNode = (TreeNode*)malloc(sizeof(TreeNode));
    treeNode->data = 3;
    treeNode->Lchild = NULL;
    treeNode->Rchild = NULL;
    treeNodeInit(2, treeNode);
    displayTreeNode(treeNode);
    int total = sumTreeNode(treeNode);
    printf("\n%d \n", total);
    return 0;
}

共有 0 条评论