输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
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:
int n = 0;
vector<int>pre;
vector<int>in;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
n = preorder.size();
if(n==0)
return nullptr;
else
{
TreeNode* ans = nullptr;
pre = preorder;
in = inorder;
create_tree(ans,0,n-1,0,n-1);
return ans;
}
}
void create_tree(TreeNode*& ans,int pre_left, int pre_right,int in_left,int in_right)
{
if(pre_left>pre_right)
return ;
int i = 0;
for(i = in_left;i<=in_right;i++)
{
if(pre[pre_left] == in[i])
break;
}
ans = new TreeNode(pre[pre_left]);
create_tree(ans->left,pre_left+1,pre_left+i-in_left,in_left,i-1);
create_tree(ans->right,pre_left+1+i-in_left,pre_right,i+1,in_right);
}
};
此题最重要的就是推导公式,根据前序遍历去找中序遍历的下标,推算出左右子树在前序遍历的范围。