这是我在SCAU数据结构上机考试中遇到的一个问题。
描述
根据给定的数据依次插入节点,构建相应的二叉排序树T(不含值重复的节点),并编写算法计算整棵树T的坡度。 一棵树的节点的坡度定义为该节点左子树的节点之和与右子树节点之和的差的绝对值。如果一个节点没有左子树,则其左子树的节点之和为0;没有右子树的话也是一样。空节点的坡度是0。 整棵树的坡度就是其所有节点的坡度之和。 示例1:
解释: 节点 1 的坡度:|0-0| = 0(没有子节点) 节点 3 的坡度:|0-0| = 0(没有子节点) 节点 2 的坡度:|1-3| = 2(左子树就是左子节点,所以和是 1 ;右子树就是右子节点,所以和是 3 ) 坡度总和:0 + 0 + 2 = 2 示例2:
解释: 节点 1 的坡度:|0-0| = 0(没有子节点) 节点 3 的坡度:|0-0| = 0(没有子节点) 节点 7 的坡度:|0-0| = 0(没有子节点) 节点 2 的坡度:|1-3| = 2(左子树就是左子节点,所以和是 1 ;右子树就是右子节点,所以和是 3 ) 节点 6 的坡度:|0-7| = 7(没有左子树,所以和是 0 ;右子树正好是右子节点,所以和是 7 ) 节点 4 的坡度:|(2+1+3)-(6+7)| = |6-13| = 7(左子树值为 2、1 和 3 ,和是 6 ;右子树值为 6 和 7 ,和是 13 ) 坡度总和:0 + 0 + 0 + 2 + 7 + 7 = 16
输入格式
第一行:二叉排序树的节点数n 第二行:n个不相同的整数
输出格式
第一行输出该二叉排序树的坡度
输入样例
3 2 1 3
输出样例
2
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#define ElemType int
#define Status int
#define OK 1
#define ERROR 0
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
Status InsertBiTree(BiTree &T, ElemType e) //插入新节点的函数
{
if (T == NULL)
{
T = (BiTNode *)malloc(sizeof(BiTNode));
T->data = e;
T->lchild = NULL;
T->rchild = NULL;
return OK;
}
if (T->data < e)
InsertBiTree(T->rchild, e);
else
InsertBiTree(T->lchild, e);
return 0;
}
int ChildrenSum(BiTree T) //求出子树T及其所有孩子结点的数据和
{
if (T)
return T->data + ChildrenSum(T->lchild) + ChildrenSum(T->rchild);
return 0;
}
int Slope(BiTree T) //求出结点T的坡度
{
int m = ChildrenSum(T->lchild);
int n = ChildrenSum(T->rchild);
return fabs(m - n);
}
int SlopeSum(BiTree T) //求出子树T的坡度
{
if (T)
return Slope(T) + SlopeSum(T->lchild) + SlopeSum(T->rchild);
return 0;
}
int main()
{
BiTree T = NULL;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) //插入数据,生成二叉排序树
{
ElemType x;
scanf("%d", &x);
InsertBiTree(T, x);
}
printf("%d", SlopeSum(T));
return 0;
}