二叉树的先序非递归创建


#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<stack>
#define ElemType char
using namespace std;

typedef struct BITREE
{
ElemType value;
struct BITREE* lchild;
struct BITREE* rchild;

}BiTree;

void createBiTree( BiTree** root )
{
stack<BiTree*> stackTree;
BiTree* pParent = NULL;
BiTree* pChild = NULL;
char str[] = "ABD*F***CE***";
int i = 0;
int flag = 0;

pParent = ( BiTree* )malloc( sizeof(BiTree) );
pParent->value = str[i];
pParent->lchild = pParent->rchild = NULL;
stackTree.push( pParent );
(*root) = pParent;

i = 1;
flag = 0;
while( !stackTree.empty() )
{
if( str[i] != '*' )
{
pParent = ( BiTree* )malloc( sizeof(BiTree) );
pParent->value = str[i];
pParent->lchild = pParent->rchild = NULL;
if( flag == 0 )
{
//insert left child
pChild = stackTree.top();
pChild->lchild = pParent;
}
else if( flag == 1 )
{
//now pChild parent need pop;
pChild = stackTree.top();
stackTree.pop();
pChild->rchild = pParent;
}
else{}
stackTree.push( pParent );
flag = 0;
}
else
{
if( flag == 0 )
{
flag = 1;

}
else if( flag == 1 )
{
stackTree.pop();
}
}
i++;
}

}

void preBiTree( BiTree* root )
{
if( NULL != root )
{
cout<<root->value<<" ";
preBiTree( root->lchild );
preBiTree( root->rchild );
}
}

int main( int argc, char* argv[] )
{
BiTree *root;

createBiTree( &root );
preBiTree( root );

return 0;
}

posted @ 2016-04-20 12:57  Blankwhite  阅读(286)  评论(0)    收藏  举报