leetcode105. 根据前序遍历和中序遍历构造二叉树
题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
根据前序遍历和中序遍历构造二叉树
思路:
- 根据前序遍历确定根结点,哈希根节点的值,得到中序遍历下标。
- 根据中序遍历下标,得到左子树大小。
- 从而确定前序遍历和中序遍历中左子树,右子树开始的位置。
/**
* 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:
unordered_map<int, int> index;
TreeNode* build(vector<int>& preorder, vector<int>& inorder, int preorder_left, int preorder_right,int inorder_left,int inorder_right)
{
if(preorder_left>preorder_right)
{
return nullptr;
}
int root_val=preorder[preorder_left];
int root_inorder=index[root_val];
TreeNode *root= new TreeNode(root_val);
int size_left = root_inorder - inorder_left;//左子树大小
root->left=build(preorder, inorder, preorder_left+1, preorder_left+size_left, inorder_left, inorder_left+size_left-1);
root->right=build(preorder,inorder,preorder_left+size_left+1,preorder_right,root_inorder+1,inorder_right);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = inorder.size();
for(int i=0;i<inorder.size();i++)
{
index[inorder[i]]=i;
}
return build(preorder, inorder, 0, n-1, 0,n-1);
}
};