1.先创建一棵树
非递归二叉树.h
利用中序和后序
int Find(char array[], int size, char v){
for (int i = 0; i < size; i++){
if (array[i] == v){
return i;
}
}
return -1;
}
Node * BuildTree2(char afterorder[], char inorder[], int size){
if (size == 0){
return NULL;
}
char rootValue = afterorder[size-1];
int leftSize = Find(inorder, size, rootValue);//i的返回值就是左子树的个数
//根
Node *root = (Node *)malloc(sizeof(Node));
root->value = rootValue;
//左子树
root->left = BuildTree2(afterorder , inorder, leftSize);
//右子树
root->right = BuildTree2(afterorder + leftSize, inorder + leftSize + 1, size - 1 - leftSize);
return root;
}
//非递归的前序遍历,利用栈去实现
#include<stack>
void preOrderNor(Node *root){
std::stack<Node *> s;
Node *cur = root;
while (cur != NULL || !s.empty()){
while (cur != NULL){
printf("%c ", cur->value);
s.push(cur);
cur = cur->left;
}
Node *top = s.top();
s.pop();
cur = top->right;
}
}
//测试
void test(){
char *inorder = "DBEAC";
char *afterorder = "DEBCA";
int size = strlen(inorder);
Node *root = BuildTree2( afterorder, inorder, size);
preOrderNor(root);
}
Main.c
#include"非递归二叉树.h"
int main(){
test();
}
结果:A B D E C 请按任意键继续. . .