二叉树的简单实现
修改为非遍历版的二叉树创建和前序遍历,修改的非常纠结啊!
#include<iostream> #include<stack> using namespace std; const int MAXSIZE = 200; struct node{ char data; node *lchild,*rchild; }; void Create_tree(node * &t){ char ch; cin >> ch; if(ch == '#') t = NULL; else{ t = new node(); t->data = ch; Create_tree(t->lchild); Create_tree(t->rchild); } } void PreOrder(node *b) { stack<node *> Stack; node *p = new node(); if(b != NULL) { Stack.push(b); while(!Stack.empty()) { p = Stack.top(); printf("%c ", p->data); Stack.pop(); if(p->rchild != NULL) Stack.push(p->rchild); if(p->lchild != NULL) Stack.push(p->lchild); } } } int main() { node *root = NULL; Create_tree(root); PreOrder(root); cout << endl; }