typedef int ElemType;
typedef struct BTree {
ElemType val;
struct BTree *left;
struct BTree *right;
} BTree, *PBTree;
PBTree makeNode(ElemType x) {
PBTree p = (PBTree)malloc(sizeof(BTree));
p->val = x;
p->left = p->right = NULL;
return p;
}
PBTree insert(ElemType x, PBTree *root) {
if (*root == NULL) return *root = makeNode(x);
if (x == (*root)->val) return NULL; // 不允許重複
if (x < (*root)->val) return insert(x, &(*root)->left);
return insert(x, &(*root)->right);
}
void preOrder(PBTree root) { // 根-左-右
if (root) {
visit(root);
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(PBTree root) { // 左-根-右
if (root) {
inOrder(root->left);
visit(root);
inOrder(root->right);
}
}
void postOrder(PBTree root) { // 左-右-根
if (root) {
postOrder(root->left);
postOrder(root->right);
visit(root);
}
}
插入序列:{21, 43, 2, 6, 88, 9}
構成樹形結構:
21
/ \
2 43
\ \
6 88
\
9
前序:21 2 6 9 43 88
中序:2 6 9 21 43 88(BST 中序為升序)
後序:9 6 2 88 43 21