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);
	}
}
  • 9
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值