Sicily 1935 二叉樹重建

2021-06-18 06:44:47 字數 757 閱讀 3267

1935. 二叉樹重建

constraints

time limit: 1 secs, memory limit: 32 mb

description

對於二叉樹t,可以遞迴定義它的先序遍歷、中序遍歷和後序遍歷如下: preorder(t)=t的根節點+preorder(t的左子樹)+preorder(t的右子樹) inorder(t)=inorder(t的左子樹)+t的根節點+inorder(t的右子樹) postorder(t)=postorder(t的左子樹)+postorder(t的右子樹)+t的根節點 其中加號表示字串連線運算。例如,對下圖所示的二叉樹,先序遍歷為dbacegf,中序遍歷為abcdefg。

輸入一棵二叉樹的先序遍歷序列和中序遍歷序列,輸出它的廣度優先遍歷序列。

input

第一行為乙個整數t(0同理前序第二個結點可以繼續將左子樹劃分為左右子樹兩個區間……這樣下去,當左邊不再存在區間時,返回上一級,對另一半的區間進行劃分,重複上述步驟,直到全部劃分完畢。用遞迴實現,之後用佇列實現bfs,輸出廣度優先遍歷序列。

**如下:

#include#include#includeusing namespace std;

string pre,in;

int index,len;

struct tree

};void rebuild(tree *&root,int st,int ed)

int main()

cout<

Sicily 1935 二叉樹重建

題目要求說的很清楚,給出乙個數的先序和中序遍歷結果,構建樹並按照廣度優先輸出。先序遍歷的第乙個數即為根節點,在中序遍歷中找到之後它左面的都是左子孫結點右邊同理。problem 1935 submission 3291146 the source code is licensed under crea...

Sicily 1935 二叉樹重建

time limit 1 secs,memory limit 32 mb 對於二叉樹t,可以遞迴定義它的先序遍歷 中序遍歷和後序遍歷如下 preorder t t的根節點 preorder t的左子樹 preorder t的右子樹 inorder t inorder t的左子樹 t的根節點 inor...

1935 二叉樹重建

這種方法簡便地利用前序遍歷和後續遍歷就得到了一顆完整的樹,雖然原理還不太清楚,但是感覺是利用了s2中lo,與hi,當不符合條件的時候才轉向右子樹。另外利用佇列進行廣度優先遍歷也是乙個亮點。include include include using namespace std int index st...