链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
思路:
使用map存储中序遍历各节点对应的下标,整个算法使用深搜思想,主要是确定各边界。k 为根结点对应的下标。
dfs左子树:前序:(pl + 1, pl + k - il) 中序(il , k - 1)
dfs右子树:前序:(pl + k - il + 1, pr) 中序(k + 1, ir)
代码:
/**
* 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> pos;
vector<int> _preorder, _inorder;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
_preorder = preorder;
_inorder = inorder;
int n = preorder.size();
for (int i = 0; i < n; ++i) pos[inorder[i]] = i;
return dfs(0, n - 1, 0, n - 1);
}
TreeNode* dfs(int pl, int pr, int il, int ir) {
if (pl > pr) return NULL;
int k = pos[_preorder[pl]];
auto left = dfs(pl + 1, pl + k - il, il , k - 1);
auto right = dfs(pl + k - il + 1, pr , k + 1, ir);
TreeNode* root = new TreeNode(_preorder[pl]);
root->left = left, root->right = right;
return root;
}
};