多叉树遍历
12:36 2012-9-25
遍历网页各框架,用到的正是递归调用.不过这个递归的样式特别些,因为以前没有见过,所以感到挺新鲜的,我叫它双函数递归.
以前的就是自己调用自己而已:
void EnumCount(int i)
{
if(i==0) return;
EnumCount(i--);
}
新的:
void Enumframe(DOM)
{
frame_count =DOM->get_frames();
if(frame_count == 0) return;
for_each(frames)
Enumform(GetDom());
}
Enumform(DOM) //入口
{
Enumframe(DOM);
...//处理各种元素
}
出现递归了,往往说明要处理的数据结构是个树形结构.
比如遍历二叉树:
struct node
{
node* left;
node* right;
}
void enum_tree(node)
{
if(node == NULL) return;
enum_tree(node->left);
enum_tree(node->right);
}
对于DOM树,子节点是多变的,不会像2,4,8叉树那样工整了,不过它更符合复杂的现实.
仿写一个:
#include <stdio.h>#include <string.h>
struct node
{char name[10];
int count; //子节点个数node* pNodeArray[]; //子节点指针数组
};void enum_node(node* pNode);
void enum_apple(node* pNode)
{enum_node(pNode);printf(pNode->name);printf("\n");
}void enum_node(node* pNode)
{int NodeCount =pNode->count;
if(NodeCount == 0) return;for(int i =0; i<NodeCount; i++)enum_apple(pNode->pNodeArray[i]);}void enum_tree()
{//创建树
node* root =new node;
root->count =2;strcpy(root->name, "ROOT");
root->pNodeArray[0] =new node;
root->pNodeArray[0]->count =2;strcpy(root->pNodeArray[0]->name, "LEFT: ");
root->pNodeArray[0]->pNodeArray[0] = new node;
root->pNodeArray[0]->pNodeArray[0]->count =0;strcpy(root->pNodeArray[0]->pNodeArray[0]->name, "LEFT_1: ");
root->pNodeArray[0]->pNodeArray[1] = new node;
root->pNodeArray[0]->pNodeArray[1]->count =0;strcpy(root->pNodeArray[0]->pNodeArray[1]->name, "LEFT_2: ");
root->pNodeArray[1] =new node;
root->pNodeArray[1]->count =4;strcpy(root->pNodeArray[1]->name, "RIGHT: ");
root->pNodeArray[1]->pNodeArray[0] = new node;
root->pNodeArray[1]->pNodeArray[0]->count =0;strcpy(root->pNodeArray[1]->pNodeArray[0]->name, "RIGHT_1: ");
root->pNodeArray[1]->pNodeArray[1] = new node;
root->pNodeArray[1]->pNodeArray[1]->count =0;strcpy(root->pNodeArray[1]->pNodeArray[1]->name, "RIGHT_2: ");
root->pNodeArray[1]->pNodeArray[2] = new node;
root->pNodeArray[1]->pNodeArray[2]->count =0;strcpy(root->pNodeArray[1]->pNodeArray[2]->name, "RIGHT_3: ");
root->pNodeArray[1]->pNodeArray[3] = new node;
root->pNodeArray[1]->pNodeArray[3]->count =0;strcpy(root->pNodeArray[1]->pNodeArray[3]->name, "RIGHT_4: ");
//遍历树
enum_apple(root);}void main()
{enum_tree();}
结论:
它的遍历方向是,先顺序遍历完子节点,在遍历上一层节点.
技巧:
递归的条件出口,写在尾函数的最前面.
posted on 2012-09-25 15:32 sinawear 阅读(11295) 评论(1) 编辑 收藏 举报