求二叉树所有结点data之和.c语言或c++

求二叉树所有结点data之和.c语言或c++代码
2025-03-07 06:15:47
推荐回答(1个)
回答1:

看代码:

#include 
#include 
#include 

typedef int data_type;  
typedef struct node  
{  
    struct node* lchild;  
    struct node* rchild;  
    data_type data;  
}BiTNode,*BiTree;

int sum(BiTree root)
{
if (root == NULL)
{
return 0;
}
// 二叉树所有结点data之和 = 根节点的data + 左子树data之和 + 右子树data之和
return root->data + sum(root->lchild) + sum(root->rchild);
}

int main()
{
BiTree root;
root = (BiTree) malloc (sizeof(BiTNode));
root->data = 1;

root->lchild = (BiTree) malloc (sizeof(BiTNode));
root->lchild->lchild = root->lchild->rchild = NULL;
root->lchild->data = 2;

root->rchild = (BiTree) malloc (sizeof(BiTNode));
root->rchild->lchild = root->rchild->rchild = NULL;
root->rchild->data = 3;

/* 上面的代码构建了一棵下面这样的二叉树
              1
             / \
            2   3
 */

printf ("sum: %d\n", sum(root));

return 0;
}