二叉树遍历

#include<iostream>
#include<queue>
#include<stack>
using namespace std;


typedef struct BNode{
int val;
struct BNode* left;
struct BNode* right;
}BNode;




BNode* create(int* pStart,int* pEnd,int* iStart,int* iEnd){
BNode* root=new BNode();
int rootVal=pStart[0];
root->val=rootVal;
root->left=root->right=NULL;

//只有一个节点,根节点
if(pStart==pEnd){
if(iStart==iEnd&&*pStart==*iStart){
return root;
}
return NULL;
}


int* iRoot=iStart;
while(iRoot<=iEnd&&*iRoot!=rootVal)
iRoot++;
int leftlen=iRoot-iStart;
if(leftlen>0){
root->left=create(pStart+1,pStart+leftlen,iStart,iRoot-1);
}
if(leftlen<pEnd-pStart){
root->right=create(pStart+leftlen+1,pEnd,iRoot+1,iEnd);
}
return root;
}


BNode* createTree(int* pStart,int* iStart,int len){
if(pStart==NULL||iStart==NULL||len<=0)
return NULL;
return create(pStart,pStart+len-1,iStart,iStart+len-1);
}


void prePrint(BNode* root){
if(root!=NULL){
cout<<root->val<<",";
}
if(root->left){
prePrint(root->left);
}
if(root->right){
prePrint(root->right);
}


}




void inPrint(BNode* root){
if(root){
if(root->left)
inPrint(root->left);
cout<<root->val<<",";
if(root->right)
inPrint(root->right);
}
}


void postPrint(BNode* root){
if(root){
if(root->left)
postPrint(root->left);
if(root->right)
postPrint(root->right);
cout<<root->val<<",";
}
}


void levelPrint(BNode* root){
if(root){
queue<BNode*> qtree;
qtree.push(root);
while(!qtree.empty()){
BNode* tmp=qtree.front();
cout<<tmp->val<<",";
qtree.pop();
if(tmp->left)
qtree.push(tmp->left);
if(tmp->right)
qtree.push(tmp->right);
}
}
}


void preP(BNode* root){
if(root){
stack<BNode*> st;
st.push(root);
while(!st.empty()){
BNode* tmp=st.top();
st.pop();
cout<<tmp->val<<",";
if(tmp->right)
st.push(tmp->right);
if(tmp->left)
st.push(tmp->left);
}
}
}


void inP(BNode* root){
//这么笨,笨笨笨!!!
stack<BNode* > st;
if(root){
st.push(root);
BNode* tmp=root->left;

while(!st.empty()||tmp){
while(tmp){
st.push(tmp);
tmp=tmp->left;
}
tmp=st.top();
st.pop();
cout<<tmp->val<<",";
tmp=tmp->right;
}
}
}


int main(){


int pre[]={1,2,4,7,3,5,6,8};
int in[]={4,7,2,1,5,3,8,6};
BNode* root=createTree(pre,in,8);
/* cout<<"前序遍历";
prePrint(root);
cout<<"\n层次遍历";
levelPrint(root);
cout<<"\n中序遍历";
inPrint(oot);
cout<<"\n非递归前序遍历:";
preP(root);
*/
inP(root);


return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值