4 重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
注意:举例子进行编程,注意边界情况,还有就是注意不要忘记递归基。
不要就举三个节点的例子,可以举七个节点的例子,得到前序和中序遍历。
4,3,1,2,5,6,7
1,3,2,4,6,5,7
/** * 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* helper(vector<int> &pre,int preBegin,int preEnd,vector<int> &vin,int vinBegin,int vinEnd){ if(preBegin > preEnd || vinBegin > vinEnd){ return nullptr; } TreeNode* root = new TreeNode(pre[preBegin]); //find left int i = 0; for(i = vinBegin;i <= vinEnd;++i){ if(vin[i] == root -> val){ break; } } root -> left = helper(pre,preBegin + 1,preBegin + i - vinBegin,vin,vinBegin,i - 1); root -> right = helper(pre,preBegin + i - vinBegin + 1,preEnd,vin,i + 1,vinEnd); return root; } TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if(pre.size() == 0){ return nullptr; } TreeNode* root = helper(pre,0,pre.size() - 1,vin,0,vin.size() - 1); return root; } };
拷贝数组的效率太低,不要看了。
/** * 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) { if(pre.size() != vin.size()){ return nullptr; } if(pre.size() == 0){//递归基 return nullptr; } TreeNode* root = new TreeNode(pre[0]); vector<int> vin_left,vin_right,pre_left,pre_right; int pos = 0; for(pos;pos < vin.size();++pos){ if(vin[pos] == root -> val){ break; } vin_left.push_back(vin[pos]); pre_left.push_back(pre[pos + 1]); } pos++; for(pos;pos < vin.size();++pos){ vin_right.push_back(vin[pos]); pre_right.push_back(pre[pos]); } root -> left = reConstructBinaryTree(pre_left,vin_left); root -> right = reConstructBinaryTree(pre_right,vin_right); return root; } };