知识大全 数据结构考研分类复习真题 第六章 答案 (五)[35]
Posted 结点
篇首语:努力尽今夕,少年犹可夸。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 数据结构考研分类复习真题 第六章 答案 (五)[35]相关的知识,希望对你有一定的参考价值。
[题目分析]按题目要求 每个结点的编号大于其左右孩子的编号 结点左孩子的编号小于右孩子的编号 由此看出 从小到大按 左右根 顺序 这正是后序遍序的顺序 故对二叉树进行后序遍历 在遍历中对结点进行编号 现将二叉树结点结构定义如下
typedef struct node ElemType data; int num; struct node *lchild *rchild; Bnode *Btree void PostOrder(Btree t) //对二叉树从 开始编号 结点编号大于其左右子女结点编号 结点的左子女编号小于其右子女编号 typedef struct Btree t; int tag; node; Btree p=t; node sn s[]; //s为栈 容量足够大 int k= top= ; //k为结点编号 top为栈顶指针 while(p!=null || top> ) while(p) sn t=p; sn tag= ; s[++top]=sn; p=p >lchild; //沿左分枝向下 while(top> && s[top] tag== )sn=s[top ];sn t >num=++k;//左右孩子已遍历 结点赋编号 if (top> ) s[top] tag= ; p=s[top] t >rchild; //while(p!=null || top> ) 结束PostOrder
[题目分析]非递归算法参考上面第 题 下面给出递归算法
void PreInCreat(BiTree root ElemType pre[] in[] int l h l h ) //根据二叉树前序序列pre和中序序列in建立二叉树 l h l h 是序列第一和最后元素下标 root=(BiTree)malloc(sizeof(BiNode)); //申请结点 root >data=pre[l ]; //pre[l ]是根 for(i=l ;i<=h ;i++) if(in[i]==pre[l ]) break; //在中序序列中 根结点将树分成左右子树 if(i==l ) root >lchild=null; //无左子树 else PreInCreat(root >lchild pre in l + l +(i l ) l i ) //递归建立左子树 if(i==h ) root >rchild=null; //无右子树 else PreInCreat((root) >rchild pre in l +(i l )+ h i+ h ) //递归建立右子树 //结束PreInCreat
cha138/Article/program/sjjg/201311/23713相关参考