一种多叉树的前序遍历C实现算法代码例子
在偶然的机会间涉及到了要对某些多未知数多方程求解其中的多数公因式的工程,然后在寻找他们的公因式时需要对其所有因式进行查找对比,由此自己感兴趣地花了几个时间写了一个小代码实现其寻找,其剖析开来就是多叉树的前序遍历算法,其中也没使用到指针,但是也是多叉树的数据结构。
我先介绍一下我当时面对的对象。如下方程式
a=b+c(d+e+t)-f(g+h(i+j));
大概是形同这样的若干个的方程式子,其中每个字母可看作一个因式,或者他们结合成因式,然后主要是对他们进行遍历查找其每个因式。
其多叉树结果如下;
针对上叙提出了前序遍历的c实现,使用双向链表:
struct Node
{
char equation;
int brother_sum;//节点的字节点数
int father; //父节点号
} ;
struct Node node[][];
struct Node current[][];
int nest = 0;
int j = 1;
int A,LA,i,b,c,k,u;
k=1;
current.equation = A;
current.rank =1;
current.brother_sum = 1;
while(nest>=0)//返回父节的兄弟点循环
{
for(j=2;j<=(current.brother_sum+1);j++)//兄弟节点循环
{
while(length(current.equation) > 1)//当前节点判断空非空循环
{
nest++;//深度数自加
for(m=1;m<=length(current.equation);m++)//循环创建子节点信息
{
child = take_child(current.equation,m);//取当前节点的子节点
node[nest][m].equation = child;//子节点自己信息
node[nest][m].brother_sum = length(current.equation);//子本节点有多少个兄弟节点
node[nest][m].father = current.rank;//当前节点排行
}
current.brother_sum = length(current.equation);//当前节点兄弟数
current.equation = node[nest][1].equation;//当前分析节点替换为子节点
current.father = current.rank;//当前节点的父亲排行
current.rank = 1;//当前节点在兄弟里的排行
}
current.equation = node[nest][j].equation;//当前节点为上一节点的兄弟
current.rank = j;//当前节点兄弟排行
}
nest--;//返回父亲层
if(nest=0)break;
current.equation = node[nest][current.father+1].equation;//取父亲的兄弟的信息
current.rank = current.father+1;//取父亲的兄弟排行
current.brother_sum = node[nest][current.father].brother_sum;
}
程序详解,下次再说吧(^ . ^)