//#ifndef __BITREE_H
//#define __BITREE_H
#include<iostream>
#include<string>
#include<stack>
#include<assert.h>
#include<stdlib.h>
using namespace std;
class BiTree;
class TreeNode
{
public:
TreeNode():left(NULL),right(NULL){}
TreeNode(char str):s(str),left(NULL),right(NULL){}
public:
friend class BiTree;
private:
char s;
TreeNode *left,*right;
};
class BiTree
{
public:
BiTree():root(NULL){}
BiTree(const string &str); //建立二叉树
~BiTree(){
Destroy(root);
}
BiTree(const BiTree& Node);
BiTree& operator=(const BiTree& Node);
bool IsEmpty(){return root==NULL?true:false;}
void CreateTree(string &s,TreeNode* Node);
void InsertNode(TreeNode *Node);
void Destroy(TreeNode *node){
if(node!=NULL)
{
Destroy(node->left);
Destroy(node->right);
delete node;
}
}
// void OutPut(ostream& out)const;
void dfs()const;
void _dfs(TreeNode*node)const;
private:
TreeNode *root;
};
//ostream& operator<<(ostream& out,const TreeNode *Node)
//{
// Node.OutPut(out);
// return out;
//}
BiTree::BiTree(const string &str)
{
string t(str);
string::const_iterator iter=t.begin();
stack<TreeNode*>s;
int k;
TreeNode *node;
char c;
root=NULL;
while(iter!=t.end())
{
//cout<<*iter<<endl;
switch(*iter)
{
case '(': s.push(node);
//cout<<"push--"<<node->s<<endl;
k=1;
break;
case ')': s.pop();
break;
case ',': k=2;
break;
default:
node=new TreeNode(*iter);
//cout<<node->s<<endl;
if(!node)
{
cout<<"Error "<<endl;
exit(0);
}
if(root==NULL)
{
root=node;
//cout<<"root--"<<root->s<<endl;
}
else
{
if(k==1)
{
TreeNode *p=s.top();
//cout<<"left:"<<node->s<<endl;
p->left=node;
}
else
{
TreeNode *p=s.top();
//cout<<"right:"<<node->s<<endl;
p->right=node;
}
}
break;
}
++iter;
}
}
/*BiTree::OutPut(ostream& out)
{
assert(root!=NULL);
out<<this->str<<"-----";
}
*/
void BiTree::_dfs(TreeNode *node)const
{
// DO WHAT U WANNA eg printf data->name or sth
// i ve been using boost::function (callback handling) but it sux (long for compile, and slower)
// so i am put result to vector
//result[rs]=v->data;
//rs++;
if(node->left!=NULL)
_dfs(node->left);
cout<<node->s<<"----";
if(node->right!=NULL)
_dfs(node->right);
}
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
void BiTree::dfs()const
{
//rs=0;
_dfs(root);
}
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
int main(int argc,char *argv)
{
string TreeStr("A(B(E(K,L),F),C(G))");
BiTree DatTree(TreeStr);
DatTree.dfs();
}
//#endif
[root@localhost ]# ./bitree
K----E----L----B----F----A----G----C----[