题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
solution:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 class Solution { 11 public: 12 TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { 13 //left-close-right-open 14 return RebuildBST(pre,vin,0,pre.size(),0,vin.size()); 15 16 } 17 TreeNode* RebuildBST(vector<int> pre,vector<int> vin,int preBegin,int preEnd,int inBegin,int inEnd) 18 { 19 if(preBegin >= preEnd || inBegin>=inEnd) return nullptr; 20 int rootCur = pre[preBegin]; 21 TreeNode* root = new TreeNode(rootCur); 22 int rootPos = 0; 23 for(rootPos = inBegin;rootPos<inEnd;rootPos++) 24 { 25 if(vin[rootPos] == rootCur) 26 { 27 break; 28 } 29 } 30 root->left = RebuildBST(pre,vin,preBegin + 1, preBegin + rootPos - inBegin + 1 ,inBegin,rootPos); 31 root->right = RebuildBST(pre,vin,preBegin + rootPos - inBegin + 1, preEnd,rootPos + 1,inEnd); 32 33 return root; 34 } 35 };
思考:
- 先序遍历提供根节点,中序遍历寻找根节点后即可成功划分子树,如此递归即可。
- 对于代码中出现的区间问题,统一采用“左开右闭”的方案,将会简化问题