標籤:style blog http color strong ar 資料 art div
二叉尋找樹按照二叉樹進行組織。二叉尋找樹關鍵字的儲存方式總是瞞住二叉尋找樹性質:
設x為二查尋找樹種一個節點。如果y是x的左子樹中的一個節點,那麼key[x] >= key[y]。如果y是x的右子樹的一個節點,那麼key[x] <= key[y]。
這樣對二叉尋找樹進行中序遍曆就可得到書中所有元素的一個非降序排列。
尋找某一個存在節點的前驅和後繼。某一個節點x的後繼就是大於key[x]的關鍵字中最小的那個節點,前驅就是小於key[x]的關鍵字中最大的那個節點。尋找二叉前驅和後繼節點的演算法如下所示:
[cpp] view plaincopyprint?
- typedef struct _node {
- struct _node *left_child;
- struct _node *right_child;
- struct _node * parent;
- ctype data;
- }node; //樹節點資料結構定義
-
- typedef node* Tree;
-
- //尋找二叉尋找樹中關鍵字最小的節點,返回指向該節點的指標
- Tree tree_minimum(Tree root)
- {
- Tree p = root;
- while (p->left_child != null)
- p = p->left_child;
- return p;
- }
-
- //尋找二叉尋找樹中關鍵字最大的節點,返回指向該節點的指標
- Tree tree_maxmum(Tree root)
- {
- Tree p = root;
-
- while (p->right_child != null)
- {
- p = p->right_child;
- }
- return p;
- }
-
- //尋找二叉尋找樹中節點x的後繼節點,返回指向該節點的指標
- //在尋找過程中,如果節點x右子樹不為空白,那麼返回右子樹的最小節點即可
- //如果節點x的右子樹為空白,那麼後繼節點為x的某一個祖先節點的父節點,而且該祖先節點是作為其父節點的左兒子
- Tree tree_successor(Tree x)
- {
- if (x->right_child != null)
- return tree_minimum(x->right_child);
-
- //x用來儲存待確定的節點
- //y為x的父節點
- Tree y = x->parent;
-
- while (y != NULL && x == y->right_child)
- {
- x = y;
- y = y->parent;
- }
- return y;
- }
-
-
- //尋找二叉尋找樹中節點x的前驅節點,返回指向該節點的指標
- //在尋找過程中,如果節點x左子樹不為空白,那麼返回左子樹的最大節點即可
- //如果節點x的左子樹為空白,那麼前驅節點為x的某一個祖先節點的父節點,而且該祖先節點是作為其父節點的右兒子
- Tree tree_predecessor(Tree x)
- {
- if (x->left_child != null)
- return tree_maxmum(x->left_child);
-
- Tree y = x->parent;
- while (y != NULL && x == y->left_child)
- {
- x = y;
- y = y->parent;
- }
- return y;
- }
二叉尋找樹的操作