面試題6 重建二叉樹

2021-06-28 20:19:41 字數 1184 閱讀 8985

/*面試題6

題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,重建出該二叉樹。不包含重複數字。

前序遍歷的第乙個結果就是根節點,中序遍歷中根節點前面的節點就是左子樹,後面的節點就是右子樹。然後遞迴的構建左右子樹。

*/binarytreenode* constructbinarynode(int* startpreorder,int* endpreorder,int* startinorder,int* endinorder);

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

binarytreenode* constructbinarynode(int* startpreorder,int* endpreorder,int* startinorder,int* endinorder)

//在中序遍歷中查詢根節點的值

int* rootinorder=startinorder;

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

++rootinorder; //找到根節點在中序中的位置

if(rootinorder==endinorder&&*rootinorder!=rootvalue)//沒有找到根節點丟擲異常

throw exception("invalid input.");

int leftlength=rootinorder-startinorder;//左子樹的長度

int* leftpreorderend=startpreorder+leftlength;//前序中左子樹的起點

if(leftlength>0)

root->m_pleft=constructbinarynode(startpreorder+1,leftpreorderend,startinorder,rootinorder-1);//構建左子樹

if(leftlengthroot->m_pright=constructbinarynode(leftpreorderend+1,endpreorder,rootinorder+1,endinorder);//構建右子樹

return root;

}/*測試用例包括:完全二叉樹,不完全二叉樹,只有左子節點的二叉樹,只有右子節點的二叉樹,只有根節點的二叉樹,根節點為null,輸入的前序和中序不匹配。*/

面試題6 重建二叉樹

templatestruct binarytreenode 對比二叉樹的圖形和其兩個遍歷序列來看,可以發現在前序遍歷序列中第乙個數字總是二叉樹的根節點的值,然後在中序遍歷序列中找到該值,它的前面就是它左子樹上節點值的集合,後面就是它右子樹上節點值的集合。由此就可以遞迴地在這兩個集合中建立二叉樹。bi...

面試題6 重建二叉樹

二叉樹中最重要的操作莫過於遍歷,即按照某一順序訪問樹中的所有結點。以下這三種遍歷都有遞迴和迴圈兩種實現方法,每一種遍歷的遞迴都要比迴圈實現簡潔地多。前序遍歷首先訪問根結點然後遍歷左子樹,最後遍歷右子樹。在遍歷左 右子樹時,仍然先訪問根結點,然後遍歷左子樹,最後遍歷右子樹。遞迴實現 void preo...

面試題6 重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二節樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。param preorder 前序遍歷 param inorder 中序遍歷 return 樹的根結點 public static binarytreenode construct int...