/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
typedef struct {
int key;
int val;
UT_hash_handle hh;
} HashItem;
HashItem *hashFindItem(HashItem **obj, int key) {
HashItem *pEntry = NULL;
HASH_FIND_INT(*obj, &key, pEntry);
return pEntry;
}
bool hashAddItem(HashItem **obj, int key, int val) {
if (hashFindItem(obj, key)) {
return false;
}
HashItem *pEntry = (HashItem *)malloc(sizeof(HashItem));
pEntry->key = key;
pEntry->val = val;
HASH_ADD_INT(*obj, key, pEntry);
return true;
}
int hashGetItem(HashItem **obj, int key, int defaultVal) {
HashItem *pEntry = hashFindItem(obj, key);
if (!pEntry) {
return defaultVal;
}
return pEntry->val;
}
void hashFree(HashItem **obj) {
HashItem *curr = NULL, *tmp = NULL;
HASH_ITER(hh, *obj, curr, tmp) {
HASH_DEL(*obj, curr);
free(curr);
}
}
struct TreeNode *createTreeNode(int val, struct TreeNode *left, struct TreeNode *right) {
struct TreeNode *obj = (struct TreeNode *)malloc(sizeof(struct TreeNode));
obj->val = val;
obj->left = left;
obj->right = right;
return obj;
}
struct TreeNode* dfs(int preLeft, int preRight, int postLeft, int postRight, int* preorder, HashItem *postMap) {
if (preLeft > preRight) {
return NULL;
}
int leftCount = 0;
if (preLeft < preRight) {
leftCount = hashGetItem(&postMap, preorder[preLeft + 1], 0) - postLeft + 1;
}
return createTreeNode(preorder[preLeft], \
dfs(preLeft + 1, preLeft + leftCount, postLeft, postLeft + leftCount - 1, preorder, postMap), \
dfs(preLeft + leftCount + 1, preRight, postLeft + leftCount, postRight - 1, preorder, postMap));
}
struct TreeNode* constructFromPrePost(int* preorder, int preorderSize, int* postorder, int postorderSize) {
int n = postorderSize;
HashItem *postMap = NULL;
for (int i = 0; i < n; i++) {
hashAddItem(&postMap, postorder[i], i);
}
struct TreeNode* root = dfs(0, n - 1, 0, n - 1, preorder, postMap);
hashFree(&postMap);
return root;
}
889. 根据前序和后序遍历构造二叉树
最新推荐文章于 2024-06-12 10:00:23 发布