資料結構之線索二叉樹的簡單實現
阿新 • • 發佈:2018-12-16
二叉樹的鏈式儲存時會有較多空間的浪費,當一顆有 n 個節點的二叉樹儲存共有2n個指標域,但是隻有n-1個被用到,所以剩下的n+1個都會被浪費掉,因此可以想一種辦法把剩餘的空間利用起來,線索二叉樹應運而生。 將二叉樹重新定義如下每個節點為下列形式 lchild ltag data rtag rchild 其中:ltag=0 時lchild指向左子女; ltag=1 時lchild指向前驅; rtag=0 時rchild指向右子女; rtag=1 時rchild指向後繼; 所以結構體可定義為:
typedef enum{ Link, Thread }PointerTag; typedef struct Tree_Node{ char ch; struct Tree_Node *left; struct Tree_Node *right; PointerTag ltag; PointerTag rtag; }Tree;
對於線索二叉樹同樣是先建立二叉樹,這裡採用先序建立和普通二叉樹相似,如下
Tree* create(){
char ch;
Tree *tree;
scanf("%c",&ch);
if(ch == '*')
tree = NULL;
else
{
tree = (Tree*)malloc(sizeof(Tree));
tree->ch = ch;
tree->left = create();
tree->right = create();
}
return tree;
}
接下來便是直接對二叉樹進行轉換處理,使其變為線索二叉樹,採用中序遍歷二叉樹的方法來建立線索二叉樹
void trans(Tree *tree){
if(tree){
trans(tree->left);
if(!tree->left){
tree->ltag = Thread;
tree->left = pre;
}
if(pre&&!pre->right){
pre->rtag = Thread;
pre->right = tree;
}
pre = tree;
trans(tree->right);
}
}
然後對線索二叉樹遍歷輸出
void print(Tree* tree){ while(tree){ while(tree->ltag == Link){ tree = tree->left; }printf("%c ",tree->ch); while(tree->rtag == Thread && tree->right != NULL){ tree = tree->right; printf("%c ",tree->ch); } tree = tree->right; } }
下面附上完整程式碼
#include <stdio.h>
#include <stdlib.h>
typedef enum{
Link,
Thread
}PointerTag;
typedef struct Tree_Node{
char ch;
struct Tree_Node *left;
struct Tree_Node *right;
PointerTag ltag;
PointerTag rtag;
}Tree;
Tree *pre;
Tree* create(){
char ch;
Tree *tree;
scanf("%c",&ch);
if(ch == '*')
tree = NULL;
else
{
tree = (Tree*)malloc(sizeof(Tree));
tree->ch = ch;
tree->left = create();
tree->right = create();
}
return tree;
}
void trans(Tree *tree){
if(tree){
trans(tree->left);
if(!tree->left){
tree->ltag = Thread;
tree->left = pre;
}
if(pre&&!pre->right){
pre->rtag = Thread;
pre->right = tree;
}
pre = tree;
trans(tree->right);
}
}
void print(Tree* tree){
while(tree){
while(tree->ltag == Link){
tree = tree->left;
}printf("%c ",tree->ch);
while(tree->rtag == Thread && tree->right != NULL){
tree = tree->right;
printf("%c ",tree->ch);
}
tree = tree->right;
}
}
int main(){
Tree *tree;
tree = create();
trans(tree);
print(tree);
}