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 * BuildTree1(char preorder[],char inorder[], int size){
if (size == 0){
return NULL;
}
char rootValue = preorder[0];
int leftSize = Find(inorder, size, rootValue);//i的返回值就是左子树的个数
//根
Node *root = (Node *)malloc(sizeof(Node));
root->value = rootValue;
//左子树
root->left = BuildTree1(preorder + 1,inorder,leftSize);
//右子树
root->right = BuildTree1(preorder + 1 + leftSize, inorder + leftSize + 1, size-1-leftSize);
return root;
}
//需要用到二个指针,last来记录被完整后序遍历过的节点
#include<stack>
void AfterOrderNor(Node *root){
std::stack<Node *> s;
Node *cur = root;
Node *last = NULL;
while (cur != NULL || !s.empty()){
while (cur != NULL){//第一次遇见
s.push(cur);
cur = cur->left;
}
//第二次遇见
Node *top = s.top();
if (top->right == NULL){
printf("%c ", top->value);
s.pop();
last = top;
}
else if (top->right == last){
printf("%c ", top->value);
s.pop();
last = top;
}
//第三次遇见
else{
cur = top->right;
}
}
}
测试:
void test(){
char *inorder = "DBEAC";
char *afterorder = "DEBCA";
int size = strlen(inorder);
Node *root = BuildTree2( afterorder, inorder, size);
AfterOrderNor(root);
}
Main.c
#include"非递归二叉树.h"
int main(){
test6();
}