自己写备忘的,还差,后续建立二叉树,后续非递归,线索化,二叉树最长路径,二叉树最远2个节点之间的距离没写。
记住一定要加
#include "stdafx.h"
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
typedef struct node{
int data;
struct node *left;
struct node *right;
}Node,*Bitree;
Bitree createTree()//前序创建二叉树
{
int ch;
Bitree t;
cin>>ch;
if(ch == 0)
return NULL;
else{
t = (Bitree)malloc(sizeof(Node));
t->data = ch;
t->left = createTree();
t->right = createTree();
return t;
}
}
void preRecur(Bitree T)//前序递归遍历二叉树
{
if(T != NULL)
{ cout<<T->data<<" ";
preRecur(T->left);
preRecur(T->right);
}
}
void inRecur(Bitree T)//中续递归遍历二叉树
{
if(T!=NULL)
{
inRecur(T->left);
cout<<T->data<<" ";
inRecur(T->right);
}
}
void inNonRecur(Bitree T)//中序非递归遍历二叉树
{
stack<Bitree> ss;
Bitree p = T;
while(p!=NULL || !ss.empty())
{
while(p!=NULL)
{
ss.push(p);
p = p->left;
}
if(!ss.empty())
{
p = ss.top();
ss.pop();
cout<<p->data<<" ";
p = p->right;
}
}
}
void preNonRecur(Bitree T)//前序非递归遍历二叉树
{
if(T == NULL)
return ;
stack<Bitree> ss;
Bitree p = T;
while(p!=NULL || !ss.empty())
{
while(p!=NULL)
{
cout<<p->data<<" ";
ss.push(p);
p = p->left;
}
if(!ss.empty())
{
p = ss.top();
ss.pop();
p = p->right;
}
}
}
void layer(Bitree T)//层序遍历二叉树
{
if(T==NULL)
return;
queue<Bitree> qu;
qu.push(T);
while(!qu.empty())
{
Bitree r = qu.front();
cout<<r->data<<" ";
qu.pop();
if(r->left!=NULL)
qu.push(r->left);
if(r->right!=NULL)
qu.push(r->right);
}
}
int depth(Bitree T)//二叉树深度
{
if(T==NULL)
return 0;
int n = depth(T->left);
int m = depth(T->right);
return m>n?(m+1):(n+1);
}
int width(Bitree T)//二叉树宽度
{
int max = 0;
if(T == NULL)
return max;
queue<Bitree> Q;
Q.push(T);
int preCount = 0;
int curCount = 1;
max = 1;
while(!Q.empty())
{
preCount = curCount;
curCount = 0;
while(preCount>0)
{
Bitree b = Q.front();
cout<<b->data<<"\t";
Q.pop();
preCount--;
if(b->left!=NULL)
{
Q.push(b->left);
curCount++;
}
if(b->right!=NULL)
{
Q.push(b->right);
curCount++;
}
}
max = curCount>max?curCount:max;
}
return max;
}
int main()
{
cout<<"Build First Tree: ";
Bitree root = createTree();
layer(root);
cout<<endl;
//cout<<"depth = "<<depth(root);
inNonRecur(root);
cout<<endl;
//layer(root);
//cout<<endl<<"width = "<<width(root)<<endl;
getchar();
getchar();
return 0;
}