Traversing the binary tree is configured in accordance with the sequence preorder a tree.
Note:
You can assume that the tree does not duplicate elements.
For example, given
Preorder inorder = [9,3,15,20,7]
Sequence after postorder traversal = [9,15,7,20,3]
Returns the following binary tree:
3
/ \
9 20
/ \
15 7
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize){
if(postorderSize==0||postorderSize!=inorderSize)return NULL;
struct TreeNode* ret=(struct TreeNode *)malloc(sizeof(struct TreeNode));
ret->val=postorder[postorderSize-1];
int left_len=0;
for(int i=0;i<inorderSize;i++)
{
if(inorder[i]==postorder[postorderSize-1])break;
left_len++;
}
assert(left_len<inorderSize);
ret->left=buildTree(inorder,left_len,postorder,left_len);
ret->right=buildTree(inorder+1+left_len,inorderSize-1-left_len,postorder+left_len,inorderSize-1-left_len);
return ret;
}
When execution: 28 ms, beat the 93.88% of all users in C submission
Memory consumption: 13.1 MB, defeated 100.00% of all users in C submission