作者:乌龟考拉互受 | 来源:互联网 | 2023-10-10 12:51
运行结果正确
其实也不难,牢牢记住栈是用来放右节点的就行了。
#include
#include
typedef struct tree_node{int val;struct tree_node *left;struct tree_node *right;
}tree;
int top=-1;
int creat_tree(tree **t){int val;scanf("%d",&val);if(val==-1){*t=NULL;}else{*t=(tree*)malloc(sizeof(struct tree_node));(*t)->val=val;printf("输入%d左节点\n",val);creat_tree(&((*t)->left));printf("输入%d右节点\n",val);creat_tree(&((*t)->right));}return 1;
}
void pre_tra(tree *t){if(t!=NULL){printf("%d ",t->val);pre_tra(t->left);pre_tra(t->right);};
}
void push(tree **base,tree *elem){base[++top]=elem;
}
void pop() {if(top==-1){return ;}top--;
}
void pre_tra1(tree *t){tree *base[20];tree *t1=t;tree *temp;push(base,t1);while(top!=-1){temp=base[top];pop();while(temp){printf("%d ",temp->val);if(temp->right){push(base,temp->right);};temp=temp->left;}}} int main(){tree *t;printf("输入根节点\n");creat_tree(&t);printf("递归遍历结果为\n");pre_tra(t);printf("\n非递归遍历结果为\n");pre_tra1(t);return 0;
}