二叉樹(確立とアクセス)(先序、中序、後序)
2904 ワード
二叉樹の建立(先序確立)
二叉樹のアクセス(再帰順と非再帰順)(再帰と非再帰的中間順)(再帰と非再帰順)
二叉樹のアクセス(再帰順と非再帰順)(再帰と非再帰的中間順)(再帰と非再帰順)
#include
#include
using namespace std;
struct Tree_Node ///
{
char data; ///
Tree_Node * left; ///
Tree_Node * right; ///
};
/// , , ,
/// , , “#”
void createTree(Tree_Node *&t)
{
char str;
cin>>str;
if(str=='#')
{
t=NULL;
}
else
{
t=new Tree_Node; /// t
t->data = str;
createTree(t->left);
createTree(t->right);
}
}
void PreorderTraverse(Tree_Node * T)/// ,
{
if(T)
{
if(T->data!='#') cout<data<left); ///
PreorderTraverse(T->right); ///
}
}
/// , :
/// : 。
/// , , , , ,
/// , ,
void PreorderTraverse_no_recursive(Tree_Node * T)
{
stack s;
Tree_Node *p = T; /// T ,
while(p || !s.empty())
{
if(p!=NULL)
{
s.push(p); ///
if(p->data!='#')///
cout<data<left; ///
}
else
{
p = s.top(); ///
s.pop();
p = p->right;///
}
}
}
void InorderTraverse(Tree_Node * T)///
{
if(T)
{
InorderTraverse(T->left); ///
if(T->data!='#') cout<data<right); ///
}
}
/// , :
/// :T , , , 。
/// T , ; , T, , T->data,
/// T 。
void InorderTraverse_recursive(Tree_Node * T)
{
stack s;
Tree_Node * p=T; /// T ,
while(p || !s.empty())
{
if(p!=NULL)
{
s.push(p); ///
p = p->left; ///
}
else
{
p=s.top(); ///
s.pop();
if(p->data!='#') cout<data<right;///
}
}
}
void PostorderTraverse(Tree_Node * T)///
{
if(T)
{
PostorderTraverse(T->left); ///
PostorderTraverse(T->right); ///
if(T->data!='#') cout<data< s;
Tree_Node *cur; /// ,
s.push(T); ///
while(!s.empty())
{
cur=s.top(); ///cur
if((cur->left==NULL && cur->right==NULL) || (pre!=NULL && (pre==cur->left || pre==cur->right)))
{
cout<data<right!=NULL) s.push(cur->right); /// ,
if(cur->left!=NULL)s.push(cur->left); ///
}
}
}
int main()
{
Tree_Node * T;
createTree(T);
cout<