1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <iostream> using namespace std;
struct BinaryTreeNode { int value; BinaryTreeNode* left; BinaryTreeNode* right; };
BinaryTreeNode* rebulidBinaryTreeCore(int* startPreOrder, int* endPreOrder, int* startInOrder, int* endInOrder) {
BinaryTreeNode* rootNode = new BinaryTreeNode(); rootNode->value = startPreOrder[0]; rootNode->left = NULL; rootNode->right = NULL;
if(startPreOrder == endPreOrder) { if(startInOrder == endInOrder && *startPreOrder == *startInOrder) { return rootNode; } else { throw ("Invalid input."); } }
int* rootIndex = startInOrder; while(rootIndex <= endInOrder && *rootIndex != rootNode->value) { rootIndex++; } if(rootIndex == endInOrder && *rootIndex != rootNode->value) { throw ("Invalid input."); }
int leftTreeLength = rootIndex - startInOrder; if(leftTreeLength > 0) { rootNode->left = rebulidBinaryTreeCore(startPreOrder + 1, startPreOrder + leftTreeLength, startInOrder, rootIndex - 1); }
if(leftTreeLength < endPreOrder - startPreOrder) { rootNode->right = rebulidBinaryTreeCore(startPreOrder + leftTreeLength + 1, endPreOrder, rootIndex + 1, endInOrder); }
return rootNode; }
BinaryTreeNode* rebulidBinaryTree(int* preOrder, int* inOrder, int n) { if(preOrder == NULL || inOrder == NULL || n <= 0) { return NULL; }
return rebulidBinaryTreeCore(preOrder, preOrder + n -1, inOrder, inOrder + n - 1); }
void printPostOrder(BinaryTreeNode* root) { if(root!= NULL) { if(root->left != NULL) { printPostOrder(root->left); } if(root->right != NULL) { printPostOrder(root->right); } cout << root->value << " "; } return ; }
int main() { int preOrder[8] = {1,2,4,7,3,5,6,8}; int inOrder[8] = {4,7,2,1,5,3,8,6}; BinaryTreeNode* root = rebulidBinaryTree(preOrder, inOrder, 8); printPostOrder(root); return 0; }
|