2007软专高级程序语言T3(前中序列构建二叉树,遍历二叉树)

设有二叉树,其结点有三个域:数值域(整形),左、右指针域,编一个函数,求给定二叉树所有结点数值域的和

如:

      -4

   5       10

-3      20     7

输出结果为:35

解题思路:

没有画图,就是求各个结点的数值域的和

前中序构建二叉树

遍历二叉树并累加数值域的值

代码如下:

#include<stdio.h>
#include<string>
#include<algorithm>
using namespace std;

typedef struct Tree
{
	int data;
	int *left;
	int *right;
}*tree;

string qx="12485309";
string zx="84251039";

tree build(string qx,string zx)//前中序构建二叉树
{
	if(qx.size()==0) return NULL;
	tree root=(tree)malloc(sizeof(Tree));
	root->data=qx[0]-'0';
	int pos=zx.find(qx[0]);
	root->left=build(qx.substr(1,pos),zx.substr(0,pos));
	root->right=build(qx.substr(pos+1),zx.substr(pos+1));
	return root;
}

int sum=0;

int qh(tree root)
{
	if(root==NULL)
	{
		return 0;
	}
	sum+=root->data;
	qh(root->left);
	qh(root->right);
	return sum;
}

int main()
{
	tree root=build(qx,zx);
	printf("%d\n",qh(root));
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值