# Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

## 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;
}
};```

## Reference

1. https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

0 条评论

## 相关文章

50630

### mac route flag 含义

https://apple.stackexchange.com/questions/336888/whats-the-meanings-of-the-routi...

22320

11030

### 逆天语言模型GPT-2最新开源：345M预训练模型和1.5B参数都来了

GPT-2，这个造假新闻编故事以假乱真，能完成阅读理解、常识推理、文字预测、文章总结等多种任务的AI模型，从诞生开始就引起大量关注。

19640

13320

54920

13530

12420

12320

9130