7 2 二叉搜尋樹的插入序列

2021-10-01 08:12:13 字數 1634 閱讀 3166

7-2 二叉搜尋樹的插入序列

二叉搜尋樹定義為:

左子樹僅包含小於根結點的元素;

右子樹僅包含大於根結點的元素;

左右子樹均為二叉搜尋樹。

一棵二叉搜尋樹可以有不同的插入順序。例如,對於如下的二叉搜尋樹

插入序列可以是 3 2 1 4 6 5, 也可以是 3 2 4 1 6 5 但不可以是 3 2 4 5 6 1。

下面給出一棵二叉搜尋樹的先序遍歷序列,請編寫程式求出該樹的插入序列個數。考慮到總數可能非常大,請輸出總數對 1000000007 (10

​9​​ +7)取餘的結果。

輸入格式:

第一行給出乙個整數 n (0第二行給出 n 個正整數,以空格分隔,表示二叉樹的先序遍歷序列;

輸出格式:

在一行中輸出插入序列總數。

輸入樣例:

63 2 1 4 6 5

輸出樣例:

10

#include

#include

int mod =

1e9+7;

struct tree

;int c[

1000][

1000];

//儲存組合數

tree charu

(int search,tree *

*now,tree *

*last)

else

if(search ==

(*now)

->num)

else

else

if(search>

(*now)

->num)}}

int num;

long

long sum =0;

struct stackstack;

void

initstack()

long

long

getnum

(tree* t)

//獲取總數

else

if(t->left !=

null

&& t->right ==

null

)//如果乙個為空乙個不為空,那麼他自己的插入方式等於他子節點的插入種類

else

if(t->left ==

null

&& t->right !=

null

)else

}int

main()

tree *tree =

(tree*

)malloc

(sizeof

(tree));

tree->right =

null

; tree->left =

null

; tree->num = root;

for(

int i=

0;i1;i++

) sum =

getnum

(tree)

;printf

("%ld"

,sum)

;}

7 2 二叉搜尋樹的插入序列

題目來自pta。二叉搜尋樹定義為 左子樹僅包含小於根結點的元素 右子樹僅包含大於根結點的元素 左右子樹均為二叉搜尋樹。一棵二叉搜尋樹可以有不同的插入順序。例如,對於如下的二叉搜尋樹 插入序列可以是 3 2 1 4 6 5,也可以是 3 2 4 1 6 5 但不可以是 3 2 4 5 6 1。下面給出...

二叉搜尋樹 插入 查詢

宣告 第一次寫二叉搜尋樹,可能會有bug 這棵二叉搜尋樹以中序遍歷的方式輸出,所以插入 儲存的規則也是按照中序遍歷的規則 include using namespace std struct node node root,nil 根節點和乙個空結點 void insert int key else ...

二叉搜尋樹的插入 刪除

二叉搜尋樹 就是每乙個結點的data值,都大於它的所有左孩子的data,小於所有右孩子的data 二叉搜尋樹的插入刪除的模擬 pragma once namespace ljc template class t friend class binarysorttree template class t...