《劍指offer》面試題7:重建二叉樹
阿新 • • 發佈:2018-12-02
題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。
二叉樹節點的定義如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
在想清楚如何在前序遍歷和中序遍歷序列中確定左、右子樹的子序列之後,可以寫出如下的遞迴程式碼:
BinaryTreeNode* Construct(int* preorder,int* inorder,int length) { if(preorder==nullptr || inorder==nullptr || length<=0) return nullptr; return ConstructCore(preorder,preorder+length-1,inorder,inorder+length-1); } BinaryTreeNode* ConstructCore(itn* startPreorder,int* endPreoder,int* startInorder,int* endInorder) { //前序遍歷序列的第一數字是根節點的值 int rootValue=startPreorder[0]; BinaryTreeNode* root=new BinaryTreeNode(); root->m_nValue=rootValue; root->m_pLeft=root->m_pRight=nullptr; //前序遍歷序列只有根節點一個數值 if(startPreorder==endPreoder) { if(startInorder==endInorder && *startPreorder==*startInorder) return root; else throw std::exception("Invalid input."); } //在中序遍歷序列中找到根節點的值 int* rootInorder=startInorder; while(rootInorder<=endInorder && *rootInorder!=rootValue) ++rootInorder; if(rootInorder==endInorder && *rootInorder!=rootValue) throw std::exception("Invalid input."); int leftLength=rootInorder-startInorder; int* leftPreorderEnd=startInorder+leftLength; if(leftLength>0) { //構建左子樹 root->m_pLeft= ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1); } if(leftLength<endPreoder-startPreorder) { //構建右子樹 root->m_pRight= ConstructCore(leftPreorderEnd+1,endPreoder,rootInorder+1,endInorder); } return root; }
測試用例:
a.普通二叉樹(完全二叉樹;不完全二叉樹)。
b.特殊二叉樹(所有節點都沒有有子節點的二叉樹;所有節點都沒有左子節點的二叉樹;只有一個節點的二叉樹)。
c.特殊輸入測試(二叉樹的根節點指標為nullptr ;輸入的前序遍歷序列和中序遍歷序列不匹配)。