输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
/**
* 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) {
TreeNode* head = nullptr;
int root;
if(!preorder.size())
return head;
head = new TreeNode(preorder[0]);
build(preorder, inorder, head);
return head;
}
void build(vector<int>& preorder, vector<int>& inorder, TreeNode* root)
{
vector<int> preleft;
vector<int> preright;
vector<int> inoleft;
vector<int> inoright;
int i = 0;
if(!preorder.size() || preorder.size() == 1)
return;
for(; i < inorder.size() && i < preorder.size(); i++) {
if(inorder[i] != root->val) {
if(preorder[i] != root->val)
preleft.emplace_back(preorder[i]);
inoleft.emplace_back(inorder[i]);
} else {
if(preorder[i] != root->val)
preleft.emplace_back(preorder[i]);
break;
}
}
i++;
for(; i < inorder.size() && i < preorder.size(); i++) {
preright.emplace_back(preorder[i]);
inoright.emplace_back(inorder[i]);
}
if(preleft.size()) {
TreeNode* left = new TreeNode(preleft[0]);
root->left = left;
build(preleft, inoleft, left);
} else {
root->left = nullptr;
}
if(preright.size()) {
TreeNode* right = new TreeNode(preright[0]);
root->right = right;
build(preright, inoright, right);
} else {
root->right = nullptr;
}
}
};
哎,不是什么好的方法,难过,空间复杂都只超过5%