二叉樹用法

2021-10-23 05:41:15 字數 2072 閱讀 2816

二叉樹的建立

二叉樹的遍歷

二叉堆的基本用法建立二叉樹(先序,中序,後序)

typedef

struct node;

typedef node *tree;

struct node

;tree bt;

void

built

(tree &bt)

// 二維指標一不小心就出錯,還是引用好

}

二叉樹的遍歷

一.三種遍歷。

void

preorder

(tree bt)

//先序遍歷,根左右。

void

inorder

(tree bt)

//中序遍歷,左根右。

void

poseorder

(tree bt)

//後序遍歷,左右根。

二.依據兩種遍歷求第三種遍歷

(無法根據先序+後序求中序)

/*

假設根節點在中序中的位置為pos,樹的結點數為len

先序, 根節點編號(0), 左子樹編號(1~pos), 右子樹編號(pos+1~len-1)

中序, 左子樹編號(0~pos-1), 根節點編號(pos), 右子樹編號(pos+1~len-1)

後序, 左子樹編號(0~pos-1), 右子樹編號(pos~len-2), 根點編號(len-1)

*/void

q_postorder

(string preorder, string inorder)

//先序+中序,實現後序.

int pos = inorder.

find

(preorder[0]

);//substr:字元擷取函式

q_postorder

(preorder.

substr(1

,pos)

, inorder.

substr(0

,pos));

//後序遍歷左子樹;

q_postorder

(preorder.

substr

(pos+

1,len-pos-1)

, inorder.

substr

(pos+

1,len-pos-1)

);//後序遍歷右子樹,pos從0開始,所以len-pos-1

cout << preorder[0]

;}void

q_preorder

(string inorder, string postorder)

//中序+後序,實現先序.

int pos = inorder.

find

(postorder[len-1]

);cout << postorder[len-1]

;q_preorder

(inorder.

substr(0

, pos)

, postorder.

substr(0

, pos));

//先序遍歷左子樹

q_preorder

(inorder.

substr

(pos+

1, len-pos-1)

, postorder.

substr

(pos, len-pos-1)

);//先序遍歷右子樹

}

二叉堆有兩種操作,插入和刪除。

// 小根堆,大根堆反過來。 

int heap[n]

;int cnt =0;

void

push

(int x)

//插入堆的值

heap[now]

= x;

}int

pop(

) heap[i]

= x;

return res;

}

二叉樹 二叉樹

題目描述 如上所示,由正整數1,2,3 組成了一顆特殊二叉樹。我們已知這個二叉樹的最後乙個結點是n。現在的問題是,結點m所在的子樹中一共包括多少個結點。比如,n 12,m 3那麼上圖中的結點13,14,15以及後面的結點都是不存在的,結點m所在子樹中包括的結點有3,6,7,12,因此結點m的所在子樹...

二叉樹的用法

include include define queue maxsize 50 typedef char data 定義元素型別 typedef struct chaintree 定義二叉樹的節點型別 chainbintree chainbintree bintreeinit chainbintre...

二叉樹的用法

定義二叉樹 include include define queue maxsize 50 typedef char data 定義元素型別 typedef struct chaintree 定義二叉樹的節點型別 chainbintree 初始化二叉樹 chainbintree bintreeini...