二叉排序數的(遞歸)定義:1、若左子樹非空,則左子樹所有節點的值均小於它的根節點;2、若右子樹非空,則右子樹所有節點的值均大於於它的根節點;3、左右子樹也分別為二叉排序樹。
如圖:
鏈表實現(比較簡單):
View Code #include <stdio.h> #include <malloc.h> typedef struct node { int data; struct node * lchild; struct node * rchild; }node; void Init(node *t) { t = NULL; } node * Insert(node *t , int key) { if(t == NULL) { node * p; p = (node *)malloc(sizeof(node)); p->data = key; p->lchild = NULL; p->rchild = NULL; t = p; } else { if(key < t->data) t->lchild = Insert(t->lchild, key); else t->rchild = Insert(t->rchild, key); } return t; //important! } node * creat(node *t) { int i, n, key; scanf("%d", &n); for(i = 0; i < n; i++) { scanf("%d", &key); t = Insert(t, key); } return t; } void InOrder(node * t) //中序遍歷輸出 { if(t != NULL) { InOrder(t->lchild); printf("%d ", t->data); InOrder(t->rchild); } } int main() { node * t = NULL; t = creat(t); InOrder(t); return 0; }
數組實現(這個有意思):
定義left[], right[]作為標記,記錄但前節點是哪個點的左(右)孩子
比如我們要對 4,3, 8,6,1。排序排好序后的二叉樹如圖:

把這個過程在紙上用筆走一遍,你就會一目了然。
My Code:
#include <stdio.h> #include <string.h> #define N 1000 int l[N], r[N], key[N], flag, root; void insert(int index, int x) { if(x <= key[index]) { if(l[index] == -1) l[index] = flag; else insert(l[index], x); } else { if(r[index] == -1) r[index] = flag; else insert(r[index], x); } } void InOrder(int index) { if(l[index] != -1) InOrder(l[index]); printf("%d ", key[index]); if(r[index] != -1) InOrder(r[index]); } int main() { int i, x, n; memset(l, -1, sizeof(l)); memset(r, -1, sizeof(r)); scanf("%d", &n); root = -1; flag = 0; for(i = 0; i < n; i++) { scanf("%d", &x); if(root == -1) key[++root] = x; else { key[++flag] = x; insert(root, x); } } InOrder(root); return 0; }
ps:轉自www.cnblogs.com/vongang
