重建二叉树

来源:互联网 发布:下载软件 知乎 编辑:程序博客网 时间:2024/05/13 07:42

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

#include <stdio.h>#include <malloc.h>#include <exception>using namespace std;typedef struct treenode{int value;struct treenode *left;struct treenode *right;}treenode,*ptreenode;ptreenode construct_core(int *preorder_start, int *preorder_end, int *inorder_start, int *inorder_end){int root_value = preorder_start[0];//前序遍历序列第一个元素是根节点ptreenode root = (ptreenode)malloc(sizeof(treenode));root->value = root_value;root->left = NULL;root->right = NULL;if(preorder_start == preorder_end){if(inorder_start == inorder_end && *preorder_start == *inorder_start)//叶子节点return root;else{throw exception("Invalid input");}}int *root_inorder = inorder_start;while(root_inorder<inorder_end && *root_inorder!=root_value)//找根节点在中序遍历序列中的位置root_inorder++;if(root_inorder == inorder_end && *root_inorder!=root_value)throw exception("Invalid input");int left_len = root_inorder - inorder_start;//子前序序列的长度if(left_len > 0){root->left = construct_core(preorder_start+1,preorder_start+left_len,inorder_start,inorder_start+left_len-1);//构建左子树}if(left_len < preorder_end - preorder_start){root->right = construct_core(preorder_start+left_len+1,preorder_end,root_inorder+1,inorder_end);//构建右子树}return root;}ptreenode construct(int a[], int b[], int length){if(a==NULL || b==NULL || length<=0)return NULL;return construct_core(a,a+length-1,b,b+length-1);}void print_tree_postorder(ptreenode head)//打印后续遍历结果{if(head == NULL)return;ptreenode p = head;print_tree_postorder(p->left);print_tree_postorder(p->right);printf("%d\t",p->value);free(p);p = NULL;}int main(){int a[] = {1,2,4,7,3,5,6,8};int b[] = {4,7,2,1,5,3,8,6};int length = sizeof(a)/sizeof(int);int i;printf("前序遍历序列为:\n");for(i=0;i<length;i++)printf("%d\t",a[i]);printf("\n");printf("中序遍历序列为:\n");for(i=0;i<length;i++)printf("%d\t",b[i]);printf("\n");ptreenode head = construct(a,b,length);if(head!=NULL){printf("重建二叉树的后续遍历结果为:\n");print_tree_postorder(head);}else{printf("重建二叉树失败!\n");}printf("\n");return 0;}


原创粉丝点击