AcWing 18. 重建二叉树C++
原题链接
中等
作者:
沙漠绿洲
,
2020-08-23 20:34:14
,
所有人可见
,
阅读 368
C++ 代码
/**
* 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> hash;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
for(int i = 0; i < n; ++ i) hash[inorder[i]] = i;
return dfs(0, 0, n - 1, preorder);
}
TreeNode* dfs(int cur, int start, int end, vector<int>& pre){
if(start > end) return nullptr;
TreeNode* root = new TreeNode(pre[cur]);
if(start == end) return root;
int mid = hash[pre[cur]]; // 找到当前根节点在中序序列中的位置
int len = mid - start; // 左子树的长度
root->left = dfs(cur + 1, start, mid - 1, pre);
root->right = dfs(cur + len + 1, mid + 1, end, pre);
return root;
}
};