# 二叉树

sun2019 发布于 2016年08月02日 22时, 0评/1102阅

Btree

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

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

```/*
* 二叉树.cpp
*
*  Created on: 2016年8月2日
*/
#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;
}
```

sun2019的其它代码