//已知二叉树的先序,中序遍历,求后续遍历 struct TreeNode { char elem; struct TreeNode* left; struct TreeNode* right; }; TreeNode* BinaryTree(char* inorder,char* preorder,int length) { if(length == 0) return NULL; TreeNode* node = new TreeNode; node->elem = *preorder; int root = 0; for(; root < length; root++){ if(inorder[root] == *preorder) break; } node->left = BinaryTree(inorder,preorder + 1,root); node->right = BinaryTree(inorder + root + 1,preorder + root + 1, length - (root + 1)); cout<<node->elem<<" "; return node; } int main() { int n; char pr[110],in[100]; while(cin>>n){ int i; for(i = 0; i < n; i++) cin>>in[i]; in[i] = ‘\0‘; for(i = 0; i < n; i++) cin>>pr[i]; pr[i] = ‘\0‘; BinaryTree(in,pr,n); cout<<endl; } return 0; }
时间: 2024-10-15 19:41:21