各種樹的構建方法

2021-08-16 23:51:53 字數 1877 閱讀 7412

已知先序中序構樹

#include #include using namespace std;  

const int n = 50;

int pre[n], in[n], post[n]; //存放先序,中序,後序的陣列

int n;//樹中元素個數

struct node ;

node* create(int prel, int prer, int inl, int inr) //根據先序和中序建立樹

node* root = new node; //建立乙個根結點,用來存放當前的樹結點

root->data = pre[prel]; // 因為是已知先序,所以當前樹的值,一定等於先序的最左邊的點

int k; //記錄當前根節點在中序的下標

for (k = inl; k <= inr; k++)

int numleft = k - inl; //當前樹的左子樹的數量

root->lchild = create(prel + 1, prel + numleft, inl, k - 1); //將這部分存入左子樹

root->rchild = create(prel + numleft + 1, prer, k + 1, inr); // 將這部分存入右子樹

return root; //返回根結點的位址,將整個樹的結點連線起來

}

已知後序中序構樹

#include #include #include using namespace std;  

const int n = 50;

int pre[n], in[n], post[n];//in中序,post後序

int n;//結點個數

struct node ;

node* create(int postl, int postr, int inl, int inr)//4個引數 後序的左右邊界,中序的左右邊界

node* root = new node; //建立乙個根結點,用來存放當前的樹結點

root->data = post[postr]; // 因為是已知後序,所以當前樹的值,一定等於先序的最右邊

int k;

for (k = inl; k<=inr; k++)

int numleft = k - inl;//當前樹的左子樹的數量

root->lchild = create(postl, postl + numleft - 1, inl, k - 1);//將這部分存入左子樹

root->rchild = create(postl + numleft, postr - 1, k + 1, inr);// 將這部分存入右子樹

return root; //返回根結點的位址,將整個樹的結點連線起來

}

先序中序後序輸出

void printfpost(node* root)                 

putchar(10);//換行

}

樹高度的求法

int gethight(node *root)
主函式

int main()

{ scanf("%d", &n);

for (int i = 0; i

樹的遍歷(各種樹)

1.靜態寫法 struct node node maxn 結點陣列,maxn為結點上限個數當需要新建乙個結點時,就按順序從陣列中取出乙個下標即可,與二叉樹的靜態實現類似 int index 0 int newnode int v 不過一般涉及 非二叉樹 的考查時,一般都給出結點的編號 2,樹的先根遍...

套題T5 各種樹

樹 tree 題目描述 方方方種下了三棵樹,一年後,第一棵樹長出了n個節點。方方方會向你提出m個詢問,每個詢問給出兩個數i,j,你需要回答 i號節點和 j號節點在樹上的距離。輸入資料 第一行兩個整數n,m。接下來 n 1行每行兩個整數a,b表示一條邊。接下來 m行每行兩個整數i,j表示詢問。輸出資料...

DS 各種樹形結構,以及其應用

紅黑樹rbtree 二叉排序樹 紅黑樹是一種自平衡二叉查詢樹,是在電腦科學中用到的一種資料結構,典型的用途是實現關聯陣列。它是在1972年由rudolf bayer發明的,他稱之為 對稱二叉b樹 它現代的名字是在 leo j.guibas 和 robert sedgewick 於1978年寫的一篇 ...