//
// Created by 18751 on 2023/5/17.
//
#include<cstdio>
#include <cstdlib>
#include <cstring>
#include<stack>
#include <iostream>
using namespace std;
typedef char ElemType;
typedef struct BtNode{
struct BtNode* leftchile;
struct BtNode* rightNode;
ElemType data;
}BtNode,*BinaryTree;
BtNode *CreateBTreePI(const char *pstr, const char *istr, int n);
int FindPos(const char *istr, int n, char temp);
void InOrder(BtNode* ptr){
if(ptr!= nullptr){
InOrder(ptr->leftchile);
printf("%c ",ptr->data);
InOrder(ptr->rightNode);
}
}
void PastOrder(BtNode* ptr){
if(ptr!= nullptr) {
PastOrder(ptr->leftchile);
PastOrder(ptr->rightNode);
printf("%c ", ptr->data);
}
}
void FrontOpder(BtNode* ptr){
if(ptr!= nullptr){
printf("%c ",ptr->data);
FrontOpder(ptr->leftchile);
FrontOpder(ptr->rightNode);
}
}
BtNode* buyNode(){
BtNode* s=(BtNode*)malloc(sizeof(BtNode));
if(nullptr==s) exit(1);
memset(s,0,sizeof(BtNode));
return s;
}
BtNode *CreateBinartTreePI(const char* pstr,const char* istr){
int n= strlen(pstr);
int m= strlen(istr);
if(nullptr==pstr|| nullptr==istr||n<1||m<1||n!=m) return nullptr;
else return CreateBTreePI(pstr,istr,n);
}
BtNode *CreateBTreePI(const char *pstr, const char *istr, int n) {
BtNode *s= nullptr;
if(n>0){
s=buyNode();
s->data=pstr[0];
int pos = FindPos(istr,n,pstr[0]);
if(-1==pos) exit(1);
s->leftchile= CreateBTreePI(pstr+1,istr,pos);
s->rightNode= CreateBTreePI(pstr+pos+1,istr+pos+1,n-pos-1);
}
return s;
}
bool NiceOrder(BtNode* ptr){
stack<BtNode* > st;
while(ptr!=NULL||!st.empty()){
while(ptr!=NULL){
st.push(ptr);
ptr = ptr->leftchile;
}
ptr=st.top();st.pop();
cout<<ptr->data<<" ";
ptr=ptr->rightNode;
}
}
int FindPos(const char *istr, int n, const char temp) {
int pos=-1;
for (int i = 0; i < n; ++i) {
if(temp==istr[i]){
pos=i;
break;
}
}
return pos;
}
int main(){
const char* pstr = "ABCDEFGH";
const char* istr = "CBEDFAGH";
BinaryTree root = CreateBinartTreePI(pstr,istr);
NiceOrder(root);
// InOrder(root);
// printf("\n");
// PastOrder(root);
// printf("\n");
// FrontOpder(root);
}
非递归中序遍历二叉树C/C++实现
最新推荐文章于 2024-08-21 18:16:36 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)