/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
// 递归
void Preorder(struct TreeNode* root, int* array, int* returnSize)
{
if (root == NULL) {
return;
}
array[(*returnSize)++] = root->val;
Preorder(root->left, array, returnSize);
Preorder(root->right, array, returnSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{
int *res = (int *)malloc(sizeof(int) * 100);
*returnSize = 0;
Preorder(root, res, returnSize);
return res;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void Postorder(struct TreeNode* root, int* array, int* returnSize)
{
if (root == NULL) {
return;
}
Postorder(root->left, array, returnSize);
Postorder(root->right, array, returnSize);
array[(*returnSize)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize)
{
int *res = (int *)malloc(sizeof(int) * 100);
*returnSize = 0;
Postorder(root, res, returnSize);
return res;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize)
{
if (preorder == NULL || inorder == NULL) {
return NULL;
}
if (preorderSize == 0 || inorderSize == 0) {
return NULL;
}
if (preorderSize != inorderSize) {
return NULL;
}
struct TreeNode *res = (struct TreeNode *)malloc(sizeof(struct TreeNode));
int rootVal = preorder[0];
int leftLen = 0;
for (int i = 0; i < inorderSize; i++) {
if (rootVal == inorder[i]) {
leftLen = i;
break;
}
}
int rightLen = inorderSize - leftLen - 1;
res->val = rootVal;
res->left = buildTree(&preorder[1], leftLen, inorder, leftLen);
res->right = buildTree(&preorder[leftLen + 1], rightLen, &inorder[leftLen + 1], rightLen);
return res;
}
/**
* 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 (inorder == NULL || postorder == NULL) {
return NULL;
}
if (inorderSize == 0 || postorderSize == 0) {
return NULL;
}
if (inorderSize != postorderSize) {
return NULL;
}
struct TreeNode* res = (struct TreeNode *)malloc(sizeof(struct TreeNode));
int rootVal = postorder[postorderSize - 1];
int leftNum = 0;
int rightNum = 0;
for (int i = 0; i < inorderSize; i++) {
if (rootVal == inorder[i]) {
leftNum = i;
break;
}
}
rightNum = inorderSize - leftNum - 1;
res->val = rootVal;
res->left = buildTree(inorder, leftNum, postorder, leftNum);
res->right = buildTree(&inorder[leftNum + 1], rightNum, &postorder[leftNum], rightNum);
return res;
}