2023-10-17 21:47:16 +08:00
|
|
|
/**
|
2023-10-18 02:16:26 +08:00
|
|
|
* File : build_tree.c
|
|
|
|
* Created Time: 2023-10-16
|
|
|
|
* Author : lucas (superrat6@gmail.com)
|
|
|
|
*/
|
2023-10-17 21:47:16 +08:00
|
|
|
|
|
|
|
#include "../utils/common.h"
|
|
|
|
|
|
|
|
// 假设所有元素都小于 1000
|
|
|
|
#define MAX_N 1000
|
|
|
|
|
|
|
|
/* 构建二叉树:分治 */
|
2023-10-18 02:16:26 +08:00
|
|
|
TreeNode *dfs(int *preorder, int *inorderMap, int i, int l, int r, int size) {
|
2023-10-17 21:47:16 +08:00
|
|
|
// 子树区间为空时终止
|
|
|
|
if (r - l < 0)
|
|
|
|
return NULL;
|
|
|
|
// 初始化根节点
|
2023-10-18 02:16:26 +08:00
|
|
|
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
|
2023-10-17 21:47:16 +08:00
|
|
|
root->val = preorder[i];
|
|
|
|
root->left = NULL;
|
|
|
|
root->right = NULL;
|
|
|
|
// 查询 m ,从而划分左右子树
|
|
|
|
int m = inorderMap[preorder[i]];
|
|
|
|
// 子问题:构建左子树
|
|
|
|
root->left = dfs(preorder, inorderMap, i + 1, l, m - 1, size);
|
|
|
|
// 子问题:构建右子树
|
|
|
|
root->right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r, size);
|
|
|
|
// 返回根节点
|
|
|
|
return root;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 构建二叉树 */
|
2023-10-18 02:16:26 +08:00
|
|
|
TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) {
|
2023-10-17 21:47:16 +08:00
|
|
|
// 初始化哈希表,存储 inorder 元素到索引的映射
|
2023-10-18 02:16:26 +08:00
|
|
|
int *inorderMap = (int *)malloc(sizeof(int) * MAX_N);
|
2023-10-17 21:47:16 +08:00
|
|
|
for (int i = 0; i < inorderSize; i++) {
|
|
|
|
inorderMap[inorder[i]] = i;
|
|
|
|
}
|
2023-10-18 02:16:26 +08:00
|
|
|
TreeNode *root = dfs(preorder, inorderMap, 0, 0, inorderSize - 1, inorderSize);
|
2023-10-17 21:47:16 +08:00
|
|
|
free(inorderMap);
|
|
|
|
return root;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
int main() {
|
|
|
|
int preorder[] = {3, 9, 2, 1, 7};
|
|
|
|
int inorder[] = {9, 3, 1, 2, 7};
|
|
|
|
int preorderSize = sizeof(preorder) / sizeof(preorder[0]);
|
|
|
|
int inorderSize = sizeof(inorder) / sizeof(inorder[0]);
|
|
|
|
printf("前序遍历 = ");
|
|
|
|
printArray(preorder, preorderSize);
|
|
|
|
printf("中序遍历 = ");
|
|
|
|
printArray(inorder, inorderSize);
|
|
|
|
|
2023-10-18 02:16:26 +08:00
|
|
|
TreeNode *root = buildTree(preorder, preorderSize, inorder, inorderSize);
|
2023-10-17 21:47:16 +08:00
|
|
|
printf("构建的二叉树为:\n");
|
|
|
|
printTree(root);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|