文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
/**
* 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) {
int current = 0;
return build(preorder, inorder, current, 0, preorder.size() - 1);
}
private:
TreeNode* build(vector<int>& preorder, vector<int>& inorder, int& current, int start, int end) {
if(current == preorder.size() || start > end) {
return nullptr;
}
int value = preorder[current];
TreeNode* node = new TreeNode(value);
int index = 0;
for(int i = start; i <= end; i++) {
if(inorder[i] == value) {
index = i;
break;
}
}
current++;
node->left = build(preorder, inorder, current, start, index - 1);
node->right = build(preorder, inorder, current, index + 1, end);
return node;
}
};