当前访客身份:游客 [ 登录 | 加入 OSCHINA ]

代码分享

当前位置:
代码分享 » C/C++  » 编程基础
sun2019

二叉树

sun2019 发布于 2016年08月02日 22时, 0评/1102阅
分享到: 
收藏 +0
0
Btree
标签: <无>

代码片段(1) [全屏查看所有代码]

1. [代码][C/C++]代码     跳至 [1] [全屏预览]

/*
 * 二叉树.cpp
 *
 *  Created on: 2016年8月2日
 *      Author: Administrator
 */
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct Btree{
	int data;
	Btree * left;
	Btree * right;
}Btree;

Btree * BT;
void Btreeinit(Btree* *h){
	*h=NULL;
	return;
};

int Btreeempty(Btree * bt){
	if(bt==NULL){
		return 1;
	}
	return 0;
}
int BTreeDepth(Btree *bt)
{
    if(bt == NULL)
    {
        return 0;
    }
    else
    {
        int d1 = BTreeDepth(bt->left);
        int d2 = BTreeDepth(bt->right);
        return (d1>d2?d1:d2)+1;
    }
}
void LeftInsert(Btree* bt1,int n){
	if(bt1==NULL){
		cerr<<"bt1 is null"<<endl;
		exit(-1);
	}
	Btree *p=new Btree;
	p->data=n;
	p->left=NULL;
	p->right=NULL;
	bt1->left=p;
}
void RightInsert(Btree* bt1,int n){
	if(bt1==NULL){
		cerr<<"bt1 is null"<<endl;
		exit(-1);
	}
	Btree *p=new Btree;
	p->data=n;
	p->left=NULL;
	p->right=NULL;
	bt1->right=p;
}
//先序遍历
void Before(Btree * bt){
	if(bt==NULL){
		return;
	}
	cout<<bt->data<<endl;
	Before(bt->left);
	Before(bt->right);
}
//中序遍历
void Midder(Btree * bt){
	if(bt==NULL){
			return;
	}
	Midder(bt->left);
	cout<<bt->data<<endl;
	Midder(bt->right);
}
//后序遍历
void After(Btree * bt){
	if(bt==NULL){
		return;
	}
	After(bt->left);
	After(bt->right);
	cout<<bt->data<<endl;
}
/*
	  			1
	  		2		3
	   	4		5
	 	  6
 */
int main()
{
	Btreeinit(&BT);
	BT = new Btree;
	BT->data=1;
	BT->left=NULL;
	BT->right=NULL;
	LeftInsert(BT,2);
	RightInsert(BT,3);
	LeftInsert(BT->left,4);
	RightInsert(BT->left,5);
	RightInsert(BT->left->left,6);
	cout<<Btreeempty(BT)<<endl;
	cout<<BTreeDepth(BT)<<endl;
	Before(BT);
	cout<<endl;
	After(BT);
	cout<<endl;
	Midder(BT);
	cout<<"hello world";
	return 0;
}


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»

开源从代码分享开始 分享代码
sun2019的其它代码 全部(9)...