题目:
代码:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode* root = new TreeNode(preorder[0]);
if(preorder[0] == -1 && inorder[0] == -1){
return root;
}
stack<TreeNode*> stk;
stk.push(root);
int inorderIndex = 0;
for(int i = 1;i < preorder.size();i++){
TreeNode* node = stk.top();
if(node->val != inorder[inorderIndex]){
node->left = new TreeNode(preorder[i]);
stk.push(node->left);
}else{
while(!stk.empty() && node->val == inorder[inorderIndex]){
node = stk.top();
stk.pop();
inorderIndex++;
}
node->right = new TreeNode(preorder[i]);
stk.push(node->right);
}
}
return root;
}
};