cpp-algo-cases/chapter_divide_and_conquer/build_tree.cpp

52 lines
1.3 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: build_tree.cpp
* Created Time: 2023-07-17
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
TreeNode *dfs(vector<int> &preorder, unordered_map<int, int> &inorderMap, int i, int l, int r) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA>ʱ<EFBFBD><CAB1>ֹ
if (r - l < 0)
return NULL;
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>
TreeNode *root = new TreeNode(preorder[i]);
// <20><>ѯ m <20><><EFBFBD>Ӷ<EFBFBD><D3B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int m = inorderMap[preorder[i]];
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E2A3BA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
root->left = dfs(preorder, inorderMap, i + 1, l, m - 1);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E2A3BA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
root->right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
// <20><><EFBFBD>ظ<EFBFBD><D8B8>ڵ<EFBFBD>
return root;
}
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>ϣ<EFBFBD><CFA3><EFBFBD><EFBFBD><EFBFBD>洢 inorder Ԫ<>ص<EFBFBD><D8B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ӳ<EFBFBD><D3B3>
unordered_map<int, int> inorderMap;
for (int i = 0; i < inorder.size(); i++) {
inorderMap[inorder[i]] = i;
}
TreeNode *root = dfs(preorder, inorderMap, 0, 0, inorder.size() - 1);
return root;
}
/* Driver Code */
int main() {
vector<int> preorder = {3, 9, 2, 1, 7};
vector<int> inorder = {9, 3, 1, 2, 7};
cout << "ǰ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> = ";
printVector(preorder);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> = ";
printVector(inorder);
TreeNode *root = buildTree(preorder, inorder);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ķ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><EFBFBD>\n";
printTree(root);
return 0;
}