设有二叉树,其结点有三个域:数值域(整形),左、右指针域,编一个函数,求给定二叉树所有结点数值域的和
如:
-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;
}