Topic description
Enter the results of preorder traversal and inorder traversal of a binary tree, and reconstruct the binary tree. It is assumed that the results of the input preorder traversal and inorder traversal do not contain duplicate numbers. For example, input the preorder traversal sequence {1,2,4,7,3,5,6,8} and the inorder traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the binary tree and return.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int vinSize = vin.size(); if(vinSize == 0) return NULL; vector<int>pre_left,pre_right,vin_left,vin_right; int val = pre[0]; int i; for(i = 0; i < vinSize; i ++) { if(vin[i] == val){ break; } } int index = i; TreeNode* tree = new TreeNode(val); for(i = 0; i < vinSize; i++ ) { if(i < index) { vin_left.push_back(vin[i]); pre_left.push_back(pre[i+1]); } else if(i > index) { vin_right.push_back(vin[i]); pre_right.push_back(pre[i]); } } tree->left = reConstructBinaryTree(pre_left,vin_left); tree->right = reConstructBinaryTree(pre_right,vin_right); return tree; } };