根据前序和中序创建二叉树
2017-11-04 20:42
851 查看
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct node* tree_pointer; typedef struct node{ tree_pointer left_child; tree_pointer right_child; char data; }tree; int find_index(char* arr,char data);//找到对应值在数组的索引 void create_tree(tree **node,char *preorder,char *inorder); int num; int Index=1;//全局变量 void post_order(tree *what) { if (what == NULL) return; post_order(what->left_child); post_order(what->right_child); printf("%c ", what->data); } int main() { char preorder[100] = {0}; char inorder[100] = {0}; printf("输入节点个数:"); scanf(" %d",&num); //i=1开始的好处是i=0设置了哨兵 //查中序遍历最左边元素的时候,最左边的元素向左边找的时候是空 //这才证明这个点没有左子树 printf("输入前序序列:"); for(int i=1;i<=num;i++) scanf(" %c",&preorder[i]); printf("输入中序序列:"); for(int i=1;i<=num;i++) scanf(" %c",&inorder[i]); tree *node; create_tree(&node,preorder,inorder); printf("后序的结果是:"); post_order(node);//后续遍历检验答案 } void create_tree(tree **node,char *preorder,char *inorder) { int find_in; (*node) = (tree *)malloc(sizeof(tree)); //前序第一个是根,所以找前序第一个,建立根节点 (*node)->data = preorder[Index];//root find_in = find_index(inorder,preorder[Index]); //找到该节点在序列中对应的位置 find_pre = 1;//原则就是服从先序的顺序,直至先序全部搜索结束 preorder[Index++] = '\0'; //每次创建一个节点,在数组中就把该节点删除,方便如何结束递归 //Index可以记录已经创建了多少节点了 inorder[find_in] = '\0';//将中序对应的值记为'\0 if(inorder[find_in-1]!='\0') //如果中序列中已经创立的节点左边有数值,证明有左子树 create_tree(&((*node)->left_child),preorder,inorder); else//没有左子树就记为空 (*node)->left_child = NULL; if(inorder[find_in+1]!='\0')//有右子树 create_tree(&((*node)->right_child),preorder,inorder); else//没有右子树就记为空 (*node)->right_child = NULL; } int find_index(char *arr,char data) { for(int i=1;i<=num;i++) //切记,这里不能用strlen,因为删除一个用'\0', //而且因为有哨兵,所以永远是0 { if(arr[i] == data) return i; } return 0; }
相关文章推荐
- 根据前序和中序创建二叉树及二叉树的前序、中序、后序、层次打印
- 根据前序和中序遍历创建二叉树
- HDU1710(根据前序和中序生成二叉树)
- 二叉树根据前序和中序确定二叉树
- 根据前序和中序重建二叉树
- [leetcode][递归] [java]105题 根据前序和中序输出二叉树
- 剑指offer_根据前序和中序确定二叉树
- 经典二叉树问题 根据前序和中序生成后序
- 根据前序和中序数组构造二叉树(递归方法)
- 对树的一些操作.比如遍历.比如.根据先序和中序创建二叉树
- 根据前序和中序建立二叉树
- 转载-根据先序序列和中序序列创建二叉树
- 根据前序和中序,构建二叉树
- 【二叉树1】根据前序和中序遍历建立一棵二叉树
- 二叉树根据先序,中序创建二叉树,后序,中序创建二叉树,层次序列,中序遍历创建二叉树。
- 二叉树根据前序和中序推出后续
- 【构建二叉树】01根据前序和中序序列构造二叉树【Construct Binary Tree from Preorder and Inorder Traversal】
- 根据前序和中序遍历的结果建立二叉树
- 根据前序和中序遍历重建二叉树
- Offer题6 根据前序和中序构建二叉树