2.6-16假设二叉树采用二叉链存储结构存放,结点值为 int 类型,设计一个递归算法求二叉树 bt 中所有叶子结点值之和

//假设二叉树采用二叉链存储结构存放,结点值为 int 类型,设计一个递归算法求
//二叉树 bt 中所有叶子结点值之和
#include "Btree.cpp"
#include <bits/stdc++.h> 

int LeafSum(BTNode *bt){
	if(bt == NULL)
		return 0;
	if(bt->lchild == NULL && bt->rchild == NULL){
		return bt->data;
	}
	int lsum = LeafSum(bt->lchild);
	int rsum = LeafSum(bt->rchild);
	return lsum + rsum;
} 

int main(){
	BTNode *bt;
	int a[]= {5,2,3,4,1,6};
	int b[]= {2,3,5,1,4,6};
	int n = sizeof(a) / sizeof(a[0]);
	bt = CreateBTree(a,b,n);
	DispBTree(bt);
	cout << endl;
	cout <<"叉树 bt 中所有叶子结点值之和为:" << LeafSum(bt);
	DestroyBTree(bt);
	return 0;
}
#include <bits/stdc++.h>

using namespace std;

typedef struct BNode {
	int data;
	struct BNode *lchild,*rchild;
}BTNode;

BTNode *CreateBTree(int a[],int b[], int n) {
	int k;
	if(n <= 0)
		return NULL; 
	BTNode *bt =(BTNode *) malloc (sizeof(BTNode));
	bt -> data = a[0];
	for(k = 0; k < n; k++)
		if(a[0] == b[k])
			break;
	//递归创建左子树
	bt -> lchild = CreateBTree(a+1, b, k);
	//递归创建左子树
	bt -> rchild = CreateBTree(a+k+1, b+k+1,n-1-k);
	return bt;
}

void DispBTree(BTNode *bt){
		if (bt != NULL){  //根左右 
			cout << bt->data << " ";
			DispBTree(bt->lchild);				
			DispBTree(bt->rchild);
		}
}	

void DestroyBTree(BTNode *bt){
	if(bt == NULL) {
		return ;
	}else{
		DestroyBTree(bt -> lchild);
		DestroyBTree(bt -> rchild);
		free(bt);
	}
}

你可能感兴趣的:(算法设计与分析)