C++练习 | 递归创建二叉树并求叶子结点的数值和
#include <iostream> using namespace std; struct Tree { int data; Tree *lchild; Tree *rchild; }tree; Tree *Create(int a1[],int b1[],int n) { int k; if(n<=0) return NULL; int root=a1[0]; Tree *bt=(Tree *)malloc(sizeof(Tree)); bt->data=root; for(k=0;k<n;k++) { if(b1[k]==root) break;//分割左右子树 } bt->lchild=Create(a1+1,b1,k); bt->rchild=Create(a1+k+1,b1+k+1,n-k-1); return bt; } int Tsum(Tree *r) { if(r->lchild==NULL&&r->rchild==NULL) return r->data; if(r->lchild==NULL&&r->rchild!=NULL) return Tsum(r->rchild); if(r->lchild!=NULL&&r->rchild==NULL) return Tsum(r->lchild); if(r->lchild!=NULL&&r->rchild!=NULL) return Tsum(r->lchild)+Tsum(r->rchild); return r->data; } int main() { Tree *rt; int sum1; int a[107],b[107],N;//N为总节点数,a为先序序列,b为中序序列 cin>>N; for(int i=0;i<N;i++) cin>>a[i]; for(int i=0;i<N;i++) cin>>b[i]; rt=Create(a,b,N);//存树 sum1=Tsum(rt); cout<<sum1<<endl; return 0; }