您的位置:首页 > 职场人生

微软面试题001-二叉树转化为链表

2011-05-17 15:38 218 查看
#include<iostream>
#include<stdlib.h>

using namespace std;

struct BSTreeNode{
BSTreeNode *pleft;
BSTreeNode *pright;
int numvaule;
};

typedef BSTreeNode DoubleList;
DoubleList *phead;
DoubleList *pListIndex;

void convert(BSTreeNode *pCurrent);

void addBSTreeNode(BSTreeNode *& pcurrent, int value)
{

if ( pcurrent == NULL)
{
BSTreeNode *pBSTree = new BSTreeNode();
pBSTree->pleft = NULL;
pBSTree->pright = NULL;
pBSTree->numvaule = value;
pcurrent = pBSTree;
}else
{
if((pcurrent->numvaule )> value)
{
addBSTreeNode( pcurrent->pleft, value);
}
else if((pcurrent->numvaule )< value)
{
addBSTreeNode( pcurrent->pright, value);
}else{
cout<<"invaild input"<<endl;
}

}
}

int ergodic(BSTreeNode *pcurrent)
{
if (NULL == pcurrent){
cout<<"The BS tree is empty"<<endl;
return -1;
}
if (NULL != pcurrent->pleft)
{
ergodic(pcurrent->pleft);
}
convert(pcurrent);

if(NULL != pcurrent->pright)
{
ergodic(pcurrent->pright);
}

return 0;
}

void convert(BSTreeNode * pcurrent)
{
pcurrent->pleft = pListIndex;
if (NULL != pListIndex){
pListIndex->pright = pcurrent;
}else{
phead = pcurrent;
}
pListIndex = pcurrent;

}

void printList(DoubleList *phead)
{
DoubleList *ptr = phead;
do{
cout<<ptr->numvaule<<endl;
ptr = ptr->pright;
}while( NULL != ptr);
}

int main(int argc, char **argv)
{
BSTreeNode *proot = NULL;

addBSTreeNode(proot, 10);
addBSTreeNode(proot, 8);
addBSTreeNode(proot, 9);
addBSTreeNode(proot, 4);
addBSTreeNode(proot, 16);
addBSTreeNode(proot, 17);
addBSTreeNode(proot, 12);
addBSTreeNode(proot, 11);
addBSTreeNode(proot, 23);

ergodic(proot);
printList(phead);

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