复习用的,防止自己忘了...
#include <iostream>
using namespace std;
// 定义二叉树节点的数据结构
typedef struct treeNode {
char data;
struct treeNode* lchild;
struct treeNode* rchild;
}treeNode;
// 先序创建二叉树
void createBinaryTree(treeNode* &T) {
char ch;
cin >> ch;
if(ch == '#') {
T = NULL;
return;
} else {
T = new treeNode;
T->data = ch;
createBinaryTree(T->lchild);
createBinaryTree(T->rchild);
}
}
// 先序遍历二叉树
void preOrderTraverse(treeNode* &T) {
if(T) {
cout << T->data << endl;
preOrderTraverse(T->lchild);
preOrderTraverse(T->rchild);
} else {
return;
}
}
// 中序遍历二叉树
void inOrderTraverse(treeNode* &T) {
if(T) {
inOrderTraverse(T->lchild);
cout << T->data << endl;
inOrderTraverse(T->rchild);
} else {
return;
}
}
// 后序遍历二叉树
void posOrderTraverse(treeNode* &T) {
if(T) {
posOrderTraverse(T->lchild);
posOrderTraverse(T->rchild);
cout << T->data << endl;
} else {
return;
}
}
int main() {
treeNode* T;
createBinaryTree(T);
preOrderTraverse(T);
inOrderTraverse(T);
posOrderTraverse(T);
return 0;
}