面試題7 重建二叉樹

2021-09-08 09:00:13 字數 2541 閱讀 2362

// 面試題7:重建二叉樹

// 題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸  

// 入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建出

// 圖所示的二叉樹並輸出它的頭結點。(假裝有圖.jpg)

// 1

// / \

// 2 3

// / / \

// 4 5 6

// \ /

// 7 8

在preorder->inorder中依次找出根節點,隨後根據inorder左右子樹的inorder和數目,來確定左右子樹的preorder。

重複這個遞迴過程,知道找到葉結點,二叉樹構建完畢。

編碼過程還需要考慮各種輸入情況,包括但不限於:

普通二叉樹、完全二叉樹、只有左子樹、只有右子樹、只有根節點、引數為nullptr、preorder與inorder輸入錯誤等等。

if(preorder與inorder為空)

return nullptr;

根據preorder建立根節點;

if(preorder與inorder長度均為1&&相等)

return 根節點;

else if(preorder與inorder長度均為1&&不相等)

throw exception;

while(inorder未遍歷完成&&inorder元素!=根節點)

if(遍歷完成&&inorder元素!=根節點)

throw exception;

if(左子樹數目》0)

根節點->左子樹=遞迴;

if(右子樹數目》0)

根節點->右子樹=遞迴

return 跟節點;

binarytreenode* construct(int* preorder, int* inorder, int length) 

binarytreenode* constructcore(int* startpreorder, int* endpreorder,

int* startinorder, int* endinorder)

//在inorder中尋找根節點的值

int* rootinorder = startinorder;

while (rootinorder <= endinorder&&*rootinorder != rootvalue)

++rootinorder;

//inorder遍歷完仍未發現根節點的值,丟擲異常

if (rootinorder == endinorder&&*rootinorder != rootvalue)

throw std::exception("invalid input!");

int leftlength = rootinorder - startinorder;

int* leftendpreorder = startpreorder + leftlength;

//根據左子樹的preorder和inorder遞迴構建左子樹

if (leftlength > 0)

root->m_pleft=constructcore(startpreorder + 1, leftendpreorder,

startinorder, rootinorder - 1);

//遞迴構建右子樹

if (leftlength < endinorder - startinorder)

root->m_pright=constructcore(leftendpreorder + 1, endpreorder,

rootinorder + 1,endinorder);

//最後一定不要忘記返回

return root;

}

關於20-26行的**,我剛開始想的是直接

if(startpreorder==endpreorder&&startinorder==endinorder&&*startpreorder==*startinorder)

,然後返回根節點,但是這樣寫的話,如果兩次根節點的值不一致,就要多出很多判斷

else if(startpreorder==endpreorder&&startinorder==endinorder&&*startpreorder!=*startinorder)

throw std::exception("");

else

所以像作者那麼寫看似多了if判斷,實際上**會更簡潔,可讀性更高,實際也不需要判斷太多。

還有後面的定義leftlength和leftendpreorder,可以減少重複的指標運算,也值得我們學習。

劍指offer第二版面試題7

posted @

2018-08-04 23:53

朕蹲廁唱忐忑 閱讀(

...)

編輯收藏

面試題7 重建二叉樹

對vector使用指標 include include include using namespace std int main vector seq 3 vector curr 0 for int j 0 j 3 j getchar struct treenode struct listnode ...

面試題7 重建二叉樹

一 題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建出圖2.6所示的二叉樹並輸出它的頭結點。二 關鍵 根據前序找根節點,從而在中序中找到左子樹對應的序列,右子樹對應的序列。三 解釋 四 i...

面試題7 重建二叉樹

題目 重建二叉樹 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如,輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並輸出它的頭節點。二叉樹節點的定義如下 struct binarytreenode 分析前序遍歷序列的第乙個數字1就是根節...