您的位置:首页 > 其它

笔试的一道题目

2008-04-27 22:12 369 查看
前几天去了一家公司应聘,以为只有面试,没有前台mm给了我两页密密麻麻的笔试题.好久没有数据结构和算法方面的实践了,硬着头皮做了接近1个半小时,狼狈地交给了她,不过,幸好面试的时候发挥得还不错,否则这人就丢大了.

里面有一道题目是: 不用递归实现中序遍历一颗二叉树,当时一门心思在想利用goto语句能不能模拟递归的方法,越想越急,最后也没有写一个好的解答,回来后,趁着今天有空,写了一个实现,算是弥补一下缺憾,也算是再次熟悉一下数据结构和算法吧.

代码如下,有一部分是初始化和释放资源,显示二叉树用的,真正的遍历是MidDescendTree函数.

#include "stdafx.h" /*just used for win VC*/
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

typedef struct tree{
struct tree * left;
struct tree * right;
int data;
}TREE;

#define MAX_TREE_DEPTH 10
int InitTree(TREE **ppTree)
{
int data;
printf("Input the data of this node: ");
scanf("%d",&data);
if(data==-1)
{
*ppTree=0;
return 0;
}
*ppTree = (TREE *)malloc(sizeof(TREE));
if(*ppTree==NULL)
{
printf("Can not get enough mem!/n");
return 1;
}
(*ppTree)->data = data;
printf("Now, init the left child of node: %d /n",data);
if(1==InitTree(&((*ppTree)->left)))
{
return 1;
}
printf("Now, init the right child of node: %d /n",data);
return InitTree(&((*ppTree)->right));
}

void PrintTree(TREE *pTree,char * pPre)
{
int len = strlen(pPre);
if(pTree==NULL)
{
return;
}

printf("%d",pTree->data);
printf("/n.%s",pPre);
if(pTree->left)
{
PrintTree(pTree->left,strcat(pPre,". "));
}
pPre[len]=0;/*经过多次递归,pPre会有累加*/
printf("/n.%s",pPre);
if(pTree->right)
{
PrintTree(pTree->right,strcat(pPre,". "));
}
pPre[len]=0;
return;
}

void KillTree(TREE *pTree)
{
if(pTree==NULL)
{
return;
}
KillTree(pTree->left);
KillTree(pTree->right);
free(pTree);
return;
}

#define PUSH_NODE(node,dir) /
{/
pHistory[lCurPos]=node;/
lDirection[lCurPos++]=dir;/
}

#define POP_NODE(node,dir) /
{/
if(lCurPos>0)/
{/
node = pHistory[--lCurPos];/
dir = lDirection[lCurPos];/
}/
else/
{/
node = NULL;/
}/
}

int MidDescendTree(TREE * pTree)
{
TREE *pHistory[100] = {0};/*to record the history of descending*/
int lDirection[100] = {0};/*0->none;1->left;2->right*/
TREE *pCurNode = pTree;
int lCurPos = 0;
int lCurDir = 1;/*current Direction: Left first*/

do
{
if(lCurDir==1)
{
if(pCurNode->left!=NULL)
{
PUSH_NODE(pCurNode,2);
/*lCurDir must be 1,so donot need to set*/
pCurNode = pCurNode->left;
continue;
}
}
if(lCurDir!=0)
{
printf("%2d ",pCurNode->data);
}
if((pCurNode->right!=NULL)&&(lCurDir!=0))
{
PUSH_NODE(pCurNode,0);
pCurNode = pCurNode->right;
lCurDir=1;/*进入一个新的节点,从左边开始遍历*/
continue;
}
POP_NODE(pCurNode,lCurDir);
}while(pCurNode);

return 1;

}

int TestTree(void)
{
int num;
char chPre[2*MAX_TREE_DEPTH+1] = {' ',' ',0};
TREE *pTree=NULL;
InitTree(&pTree);
PrintTree(pTree,chPre);
printf("/n");

MidDescendTree(pTree);

KillTree(pTree);
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: