4.重建二叉树——剑指offer
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 //递归思想 11 //前序遍历:中左右 中序遍历:左中右 12 //通过前序的第一个值找到中心结点,得到前序和中序的左子树和又子树 13 //递归左子树和又子树 14 class Solution { 15 public: 16 TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { 17 int length = pre.size(); 18 if(length == 0) return NULL; 19 int root = pre[0]; 20 int index; 21 vector<int> pre_left , pre_right , vin_left , vin_right; 22 for(int i = 0;i < length; ++i){ 23 if(root == vin[i]){ 24 index = i; 25 break; 26 } 27 } 28 for(int i = 0; i < index; ++i){ 29 pre_left.push_back(pre[i+1]); 30 vin_left.push_back(vin[i]); 31 } 32 for(int i = index + 1;i < length; ++i){ 33 pre_right.push_back(pre[i]); 34 vin_right.push_back(vin[i]); 35 } 36 TreeNode* node = new TreeNode(root); 37 node->left = reConstructBinaryTree(pre_left , vin_left); 38 node->right = reConstructBinaryTree(pre_right , vin_right); 39 return node; 40 } 41 };