Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Accept: 22ms
思路:
- 中根遍历+后根遍历还原一棵二叉树。
- top为当前栈顶元素,然后从中根里找到对应的元素的位置,作为新的中根元素,与top里记录的当前中根左右两端做比较:
- 如果新的中根在右边,则插入到右子树,并且新中根入栈;
- 如果新的中根在左边,则插入到左子树,并且新中根入栈;
- 否则,弹出top,然后重新比较左右2端。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct Elem {
struct TreeNode* node;
int left_beg;
int left_end;
int right_beg;
int right_end;
};
int find(int* inorder, int left, int right, int val) {
for (int i = left; i < right; ++i) {
if (inorder[i] == val) {
return i;
}
}
return -1;
}
int push(struct Elem* stack, int* p, struct TreeNode *node,
int left, int mid, int right) {
stack[*p].node = node;
stack[*p].left_beg = left;
stack[*p].left_end = mid;
stack[*p].right_beg = mid + 1;
stack[*p].right_end = right;
++*p;
}
struct TreeNode* makeNode(int val) {
struct TreeNode* node = malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
struct TreeNode *buildTree(int *inorder, int *postorder, int n) {
if (n == 0) {
return NULL;
}
const int max_size = 10000;
struct Elem stack[max_size];
int p = 0;
struct TreeNode* head = makeNode(postorder[n-1]);
int mid = find(inorder, 0, n, head->val);
push(stack, &p, head, 0, mid, n);
int i = n - 2;
while (i >= 0) {
int val = postorder[i];
struct Elem *top = &stack[p - 1];
int mid = find(inorder, top->right_beg, top->right_end, val);
if (mid >= 0) {
struct TreeNode *node = makeNode(val);
top->node->right = node;
push(stack, &p, node, top->right_beg, mid, top->right_end);
--i;
continue;
}
mid = find(inorder, top->left_beg, top->left_end, val);
if (mid >= 0) {
struct TreeNode *node = makeNode(val);
top->node->left = node;
push(stack, &p, node, top->left_beg, mid, top->left_end);
--i;
continue;
}
// pop:
p--;
} // while
return head;
}