题目描述
知识点
树,递归
我的实现
结果
码前思考
- 模板题
代码实现
/**
* 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* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* build(vector<int>& preorder,int preL,int preR,vector<int>& inorder,int inL,int inR){
if(preL>preR){
return NULL;
}
//首先得到当前的根节点
int val = preorder[preL];
//printf("%d\n",val);
TreeNode* root = new TreeNode(val);
//找到分割点
int k = 0;
while(inorder[inL+k]!=preorder[preL]){
k++;
}
root->left = build(preorder,preL+1,preL+k,inorder,inL,inL+k-1);
root->right = build(preorder,preL+k+1,preR,inorder,inL+k+1,inR);
return root;
}
};
码后反思
- 模板题注意思考清楚;