二叉树---数据结构

#include"stdafx.h"
#include<iostream>
#include<assert.h>
#include<stdlib.h>
using namespace std;
typedef int Elemtype;
typedef struct Tree{

	Elemtype data;     // 存放数据域
	struct Tree *lchild;   // 遍历左子树指针
	struct Tree *rchild;   // 遍历右子树指针

}BNode, *BTree;
BTree Creat_BiTree(){
	int data;

	cin >> data;
	BNode* root = (BTree)malloc(sizeof(BNode));
	if (data == -1) return NULL;
	else{
		root->data = data;
		cout << "请输入" << data << "左节点的数值" << endl;
		root->lchild = Creat_BiTree();
		cout << "请输入" << data << "右节点的数值" << endl;
		root->rchild = Creat_BiTree();
	}
	return root;
}
//先序排列
void PreOrder(BTree root){
	if (root== NULL){
		return;
	}
	cout << root->data << "   ";
	PreOrder(root->lchild);
	PreOrder(root->rchild);
}
//中序排列
void InOrder(BTree root){
	if (root == NULL){
		return;
	}
	InOrder(root->lchild);
	cout << root->data << "   ";
	InOrder(root->rchild);
}

//后续遍历

void PostOrder(BTree root){
	if (root == NULL){
			return;
	}
	PostOrder(root->lchild);
	PostOrder(root->rchild);
	cout << root->data << "   ";

}
int sum = 0;
//先序遍历输出叶子节点
void Leaf(BTree root){
	if (root == NULL) return;
	if (root->lchild == NULL&&root->rchild == NULL){
		cout << endl<<root->data << endl;
		sum++;
	}
	Leaf(root->lchild);
	Leaf(root->rchild);
}
//求二叉树的高度(递归算法)
void  height(BTree root, int h,int *p){
	if (root != NULL){
		if (h > *p){
			*p = h;
		}
		height(root->lchild , h + 1,p);
		height(root->rchild, h + 1,p);
	}

}

int main(){
	cout << "请输入根节点的数值:" << endl;
	BTree root = Creat_BiTree();
	cout << "先序遍历" << endl;
	PreOrder(root);
	cout << endl;
	cout << "中序遍历" << endl;
	InOrder(root);
	cout << endl;
	cout << "后序遍历" << endl;
	PostOrder(root);
	cout << endl;
	cout << "叶子节点为" ;
	Leaf(root);
	cout << "叶子节点个数为" << endl << sum;
	int x=0;
	height(root, 1,&x);
	cout << endl << "二叉树的高度为:"<<x<< endl;
	cout <<endl<< "容颜如玉,身姿如松,翩若惊鸿,婉若游龙。" << endl; 
}

 我爱柚子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值