劍指offer 先序 中序遍歷結果重建二叉樹

2021-07-26 17:09:03 字數 1296 閱讀 4388

題目

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。

#include 

#include

#include

using

namespace

std;

struct treenode

};//建立二叉樹演算法

treenode* reconstructbinarytree(vector

pre, vector

mid)

}for (int i = 0; i < nodesize; i++)

else

if (i > rootpos)

}phead->left = reconstructbinarytree(leftpre, leftmid);

phead->right = reconstructbinarytree(rightpre, rightmid);

return phead;

}//列印後續遍歷順序

void printnodevalue(treenode* root)

printnodevalue(root->left);

printnodevalue(root->right);

cout

<< root->val<< " ";

}int main()

; vector

midvec;

cout

<< "先序遍歷序列為 1 2 4 5 3 6"

<< endl;

cout

<< "中序遍歷序列為 4 2 5 1 6 3"

<< endl;

treenode* root = reconstructbinarytree(prevec, midvec);

cout

<< "後續遍歷序列為 ";

printnodevalue(root);

cout

<< endl;

system("pause");}/*

測試二叉樹形狀:

12 3

4 5 6

*/

執行結果:

先序遍歷序列為 1 2 4 5 3 6

中序遍歷序列為 4 2 5 1 6 3

後續遍歷序列為 4 5 2 6 3 1

請按任意鍵繼續. . .

部落格295 由先序遍歷結果和中序遍歷結果建立樹

內容 根據先序遍歷和中序遍歷結果來建立一棵樹 思路 1 每次遞迴建立樹的左右子樹 2 由先序遍歷的第乙個資料就是根節點,然後這個節點在中序遍歷的位置的左邊為樹的左子樹成員,右邊為右子樹成員 由此可以劃分樹的左右子樹部分,進行遞迴處理 先序中序建樹 include include include in...

樹 先序中序後序遍歷

題目分析 題目描述 description 求一棵二叉樹的前序遍歷,中序遍歷和後序遍歷 輸入描述 input description 第一行乙個整數n,表示這棵樹的節點個數。接下來n行每行2個整數l和r。第i行的兩個整數li和ri代表編號為i的節點的左兒子編號和右兒子編號。輸出描述 output d...

劍指offer 根據前序遍歷和中序遍歷確定樹

題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。思路 注意 前序遍歷和中序遍歷時根節點和左子樹都在右子樹前面。所以根據前序遍歷確定根節點,再根據在中序遍歷確定左右子樹的元...