遍历算法的应用

一、输出二叉树中的结点

typedef struct Node {
	DataType data;
	struct Node *LChild;
	struct Node *RChild;
} BiTNode,*BiTree;

viod PreOrder(BiTree root) {
	if(root!=NULL) {
		printf(root->data);     /*先序遍历输出根结点 */
		PreOrder(root->LChild);
		PreOrder(root->RChild);
	}
}

二、输出二叉树中的叶子结点

void PreOrder(BiTree root) {
	if(root!=NULL) {
		if(root->LChild==NULL&&root->RChild==NULL)
		Printf(root->data);     /*先序遍历输出叶子结点 */
		PreOrder(root->LChild);
		PreOrder(root->RChild);
	}
}

三、统计叶子结点的数目
1 后序遍历

void Leaf(BiTree root) {
	int LeafCount;
	if(root!=NULL) {
		Leaf(root->LChild);
		Leaf(root->RChild);
		if(root->LChild==NULL&&root->RChild==NULL)
		LeafCounti++;
	}
}

2 后序遍历

void Leaf(BiTree root) {
    int LeafCount;
	if(root!=NULL) {
		Leaf(root->LChild);
		Leaf(root->RChild);
		if(root->LChild==NULL&&root->RChild==NULL)
		LeafCount++;
	}
}

3

void Leaf(BiTree root) {
	int LeafCount;
	if(root!=NULL) 
	 LeafCount=0;
	else if(root->LChild==NULL&&root->RChild==NULL)
		LeafCount=1;
	else
	LeafCount=leaf(root->LChild)+leaf(root->RChild);//左右子树叶子数目之和
	return Leaf(root->RChild);
	}
}

四、后序遍历发求二叉树的高度

int PostTreeDepth(BiTree bt) {
	int hl,hr,max;
	if(bt!=NULL) {
		hl=PostTreeDepth(bt->LChild); //求左子树深度
		hr=PostTreeDepth(bt->RChild);//求右子树深度
		max=hl>hr?hl:hr;
		return(max+1);				//返回树的深度
	} else
		return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值