标签:size 序列 中序 递归 bre for 中序遍历 构造 ||
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* recursion(vector<int> pre,vector<int> vin, int preBegin, int vinBegin, int vinEnd){
if(preBegin>=pre.size() || vinBegin>=vinEnd) return NULL;
TreeNode* res=new TreeNode(pre[preBegin]);
for(int i=vinBegin; i<vinEnd; i++){
if(vin[i]==pre[preBegin]){
res->left=recursion(pre, vin, preBegin+1, vinBegin, i);
res->right=recursion(pre, vin, preBegin+(i-vinBegin)+1, i+1, vinEnd);
break;
}
}
return res;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()==0 || inorder.size()==0 || preorder.size()!=inorder.size()) return NULL;
return recursion(preorder, inorder, 0, 0, inorder.size());
}
};
2020.5.4 从前序与中序遍历序列构造二叉树 中等 105
标签:size 序列 中序 递归 bre for 中序遍历 构造 ||
原文地址:https://www.cnblogs.com/wasi-991017/p/12827005.html