////////////////////////////////////////////////// /////////////////////////////////////
// // 9. topic six: rebuild binary tree
// Title: and enter the result in a preorder traversal of a binary tree in preorder traversal of a binary tree to change the rebuild
struct BinaryTreeNode { int m_iValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight; BinaryTreeNode(int iValue = 0, BinaryTreeNode* pLeft = NULL, BinaryTreeNode* pRight = NULL) :m_iValue(iValue), m_pLeft(pLeft), m_pRight(pRight) { } }; BinaryTreeNode* RebuildTree(int* pPreStart, int* pPreEnd, int* pInStart, int* pInEnd) { if (pPreStart > pPreEnd || pInStart >pInEnd) { return NULL; } // 1. establish a root node (a preorder traversal of the first element) BinaryTreeNode * = PROOT new new BinaryTreeNode (* pPreStart); IF ! ( PROOT) { return NULL; } // 2. Locate root sequence int * P = pInStart; the while (P <= P * = pRoot- pInEnd &&!> m_iValue) { P ++ ; } int iLeftLength = P - pInStart; int * pLeftPreEnd + = pPreStart iLeftLength; // . 3. Construction of the left subtree if (iLeftLength > 0) { pRoot->m_pLeft = RebuildTree(pPreStart + 1, pLeftPreEnd, pInStart, p - 1); } // 4.构建右子树 if (iLeftLength < (pPreEnd - pPreStart)) { pRoot->m_pRight = RebuildTree(pLeftPreEnd + 1, pPreEnd, p + 1, pInEnd); } return pRoot; } BinaryTreeNode* RebuildBinaryTree(int* piPreOrderArray, int* piInorderArray, int iLength) { if (NULL == piPreOrderArray || NULL == piInorderArray || iLength <= 0) { return NULL; } return RebuildTree(piPreOrderArray, piPreOrderArray + iLength - 1, piInorderArray, piInorderArray + iLength -1); } void DestroyTree(BinaryTreeNode* pTree) { if (pTree) { // 释放左子树 DestroyTree(pTree->m_pLeft); // 释放右子树 DestroyTree(pTree->m_pRight); delete pTree; pTree = NULL; } } // 后序遍历 void PostTraversal(BinaryTreeNode* pNode) { if (pNode) { PostTraversal(pNode->m_pLeft); PostTraversal(pNode->m_pRight); printf("%02d -> ", pNode->m_iValue); } } void RebuildBinaryTreeTestFunc() { cout << "\n\n --------------- RebuildBinaryTreeTestFunc Start -------------->" << endl; const int MAX_TREE_NODE_COUNT = 8; // preorder traversal sequence (in -> Left -> right) front int aiPreOrderArray [MAX_TREE_NODE_COUNT] = { . 1 , 2 , . 4 , . 7 , . 3 , . 5 , . 6 , . 8 }; // preorder sequence (left - in> -> Right) int aiInorderArray [MAX_TREE_NODE_COUNT] = { . 4 , . 7 , 2 , . 1 , . 5 , . 3 , . 8 , . 6 }; // postorder sequence (left -> Right -> the) int aiPostArray [MAX_TREE_NODE_COUNT] = { 7 , 4, 2, 5, 8, 6, 3, 1}; BinaryTreeNode* pTree1 = RebuildBinaryTree(aiPreOrderArray, aiInorderArray, MAX_TREE_NODE_COUNT); if (pTree1) { // 后序遍历 PostTraversal(pTree1); putchar(10); // 施法资源 DestroyTree(pTree1); } cout << "\n\n --------------- RebuildBinaryTreeTestFunc End -------------->" << endl; }