已知一棵二叉树的后序遍历序列和中序遍历序列,写出可以确定这棵二叉树的算法。
输入
dabec# //后序序列,其中#代表结束符
debac# //中序序列,其中#代表结束符
输出
ce0db00000a0000 //满二叉树形式输出(就是按照从上到下,从左到右的形式输出一颗满二叉树)
输入输出样例:1组
#1
dabec# //后序序列,其中#代表结束符
debac# //中序序列,其中#代表结束符
ce0db00000a0000 //满二叉树形式输出
参考代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX 100typedef struct tree
{char data;struct tree *lchild , *rchild;
} BinNode,*BiTree;BiTree restore(char* zhong, char *hou, int length)
{//后序中序恢复二叉树if(length == 0){return NULL;}BiTree node;node = (BinNode *)malloc(sizeof(BinNode));node->data= *(hou+length-1);int rootIndex = 0;for(;rootIndex < length; rootIndex++){if(zhong[rootIndex] == *(hou+length-1))break;}node->lchild = restore(zhong, hou , rootIndex);node->rchild = restore(zhong + rootIndex + 1, hou + rootIndex , length - (rootIndex + 1));//中序中根节点右边的点,在后序中也一定在后边return node;
}
int Height_tree(BiTree T)
{//获得当前树的高度int r,l;if (T == NULL){return 0;}l = Height_tree(T->lchild);r = Height_tree(T->rchild);return l>=r?l+1:r+1;
}void Levelorder(BiTree T, BinNode *queue[],char c[],int height)
{//层次遍历输出满二叉树,T代表树的根,queue代表层次队列,c是输出的序列(从1开始存储),height是代表树的高度BinNode *p;int front,rear;int i =1;if(T == NULL){return;}rear = 0;front = -1;queue[rear] = T;c[1] = T->data;while(front != rear){ //只要队列不空front++; //准备出队if(queue[front]==NULL)//如果当前队列出队为空,则将其左右空孩子都入队,并且放入输出数组中{c[++i]='0';
本文发布于:2024-02-01 21:16:47,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170679340739474.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |