重建一棵二叉樹
阿新 • • 發佈:2018-12-28
根據先序,中序重建一棵二叉樹;
思路:中序確定根節點,遞迴到葉子,在回溯建樹
程式碼:
#include <iostream> #include <assert.h> using namespace std; typedef char Datatype; struct BiTreeNode { Datatype m_nData; BiTreeNode *m_pLeftChild; BiTreeNode *m_pRightChild; }; BiTreeNode* CreateBiTreeByPreorderAndInorder(Datatype* preOrder, int nPreStart,int nPreEnd ,Datatype* inOrder, int nInStart, int nInEnd) { if (nPreStart > nPreEnd) { return NULL; } //根據序序列找到根結點 Datatype nRootDate = preOrder[nPreStart]; //在中序序列中找到根結點 int nCount = 0; int nCur = 0; for (nCur=nInStart; nCur<=nInEnd; nCur++) { if (nRootDate != inOrder[nCur]) { nCount++;//nCount記錄左子樹的結點個數 } else { break; } } //建立結點 assert(nCur >= nInStart && nCur <= nInEnd); BiTreeNode* pRoot = new BiTreeNode; pRoot->m_nData = nRootDate; //根據中序序列,劃分兩個序列,遞迴處理。 pRoot->m_pLeftChild = CreateBiTreeByPreorderAndInorder(preOrder,nPreStart+1,nPreStart+nCount ,inOrder,nInStart,nInStart+nCount-1); pRoot->m_pRightChild = CreateBiTreeByPreorderAndInorder(preOrder, nPreStart+nCount+1, nPreEnd ,inOrder, nInStart+nCount+1,nInEnd); return pRoot; } //根據二叉樹的中序遍歷序列和後序遍歷序列重建二叉樹 BiTreeNode * CreateBiTreeByPreorderAndInorder(Datatype *preOrder, Datatype *inOrder, int nLength) { //for(int i=0;i<nLength;i++) cout<<preOrder[i]<<" "; if ((preOrder!=NULL) && (inOrder!=NULL) && (nLength>0)) { return CreateBiTreeByPreorderAndInorder(preOrder, 0,nLength-2,inOrder, 0, nLength-2); } else { return NULL; } } void PosOrderPrint(BiTreeNode *pRoot) { if (pRoot != NULL) { PosOrderPrint(pRoot->m_pLeftChild); PosOrderPrint(pRoot->m_pRightChild); cout << pRoot->m_nData << " "; } } void InOrderPrint(BiTreeNode *pRoot) { if (pRoot != NULL) { InOrderPrint(pRoot->m_pLeftChild); cout << pRoot->m_nData << " "; InOrderPrint(pRoot->m_pRightChild); } } void PreOrderPrint(BiTreeNode *pRoot) { if (pRoot != NULL) { cout << pRoot->m_nData << " "; PreOrderPrint(pRoot->m_pLeftChild); PreOrderPrint(pRoot->m_pRightChild); } } int main() { Datatype nInOrderArr[10] = {'C','B','E','D','A','F','I','G','H'}; Datatype nPreOrderArr[10] = {'A','B','C','D','E','G','F','I','H'}; BiTreeNode *pRoot = CreateBiTreeByPreorderAndInorder(nPreOrderArr, nInOrderArr,10); cout << "前序序列:"; PreOrderPrint(pRoot); cout<<endl; cout << "中序序列:"; InOrderPrint(pRoot); cout << endl; cout << "後序序列:"; PosOrderPrint(pRoot); cout << endl; return 0; }