标签:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
#include<stdio.h> #include<stdlib.h> typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }TreeNode; TreeNode *buildTreeCore(int *inorder, int inbegin, int inend, int *postorder, int postbegin, int postend) { TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode)); root->val = postorder[postend]; root->left = root->right = NULL; if(inbegin == inend || postbegin == postend) return root; int i; for(i = inend; i >= inbegin && postorder[postend] != inorder[i]; i--) ; if(i < inend) { root->right = buildTreeCore(inorder, i + 1, inend, postorder, postbegin + i - inbegin, postend - 1); } if(i > inbegin) { root->left = buildTreeCore(inorder, inbegin, i - 1, postorder, postbegin, postbegin + i - inbegin - 1); } return root; } TreeNode *buildTree(int *inorder, int *postorder, int n) { if(inorder == NULL || postorder == NULL) return NULL; TreeNode *root = buildTreeCore(inorder, 0, n - 1, postorder, 0, n - 1); } void Travel(TreeNode *root) { if(root != NULL) { printf("%d, ", root->val); Travel(root->left); Travel(root->right); } } void main() { int in[] = {1, 2, 3, 4, 5, 6}; int post[] = {1, 2, 4, 5, 6, 3}; TreeNode *root = buildTree(in, post, 6); Travel(root); printf("\n"); }
Construct Binary Tree from Inorder and Postorder Traversal
标签:
原文地址:http://blog.csdn.net/uj_mosquito/article/details/43309807