Home > Back-end >  Binary tree
Binary tree

Time:11-09


#include

using namespace std;

Struct BiNode

{

char data;

Rchild BiNode * and * lchild;

};

The class BiTree

{

Public:

BiTree () {root=Creat (root); }//constructor, the establishment of a binary tree

~ BiTree () {Release (root); }//destructors, release of each node storage

Void the Pre () {PreOrder (root); }//preorder traversal

Void (In) {InOrder (root); }//in the sequence traversal

Void Psot () {PostOrder (root); }//after sequence traversal

Private:

char ch;

BiNode * root;//pointer to the head of the root node

Creat BiNode * (bt) BiNode *;

Void Release (bt) BiNode *;

Void PreOrder BiNode * (bt);

Void InOrder BiNode * (bt);

Void PostOrder BiNode * (bt);//total of member function call

};

BiNode * BiTree: : Creat (bt) BiNode *

{

Cin & gt;> Ch;//data input nodes information

If (ch=='#') bt=NULL;//set up an empty tree, when the input "#" said to leaf node

The else {

Bt=new BiNode; Bt - & gt; Data=https://bbs.csdn.net/topics/ch;//generated nodes, the input value is assigned to the data

Bt - & gt; Lchild=Creat (bt - & gt; Lchild);

Bt - & gt; Rchild=Creat (bt - & gt; Rchild);//recursive set up left and right subtrees

}

The return of bt;

}

Void BiTree: : Release (bt) BiNode *

{

If (bt!!!!=NULL) {

Release (bt - & gt; Lchild);

Release (bt - & gt; Rchild);//recursive release about subtree, starting from the leaf node release

Delete the bt;//release the root node

}

}

Void BiTree: : PreOrder BiNode * (bt)

{

BiNode * s [10].

Int top=1; Does not occur, assumes that//in a sequential stack overflow

While (bt!!!!=NULL | | top!=1)//jump out of the loop condition, no leaf node and the stack is empty

{

While (bt!!!!=NULL)//until the leaf node

{

Cout & lt;
S [+ + top]=bt;//root stack pointer into the

Bt=bt - & gt; Lchild;

}

If (top!=1)//when the stack is not empty

{

Bt=s [top -];//out of the stack,

Bt=bt - & gt; Rchild;

}

}

}

Void BiTree: : InOrder BiNode * (bt)//in sequence with the traversal sequence similar, slightly differ

{

BiNode * s [10].

Int top=1;

While (bt!!!!=NULL | | top!=1)

{

While (bt!!!!=NULL)

{

S [+ + top]=bt;

Bt=bt - & gt; Lchild;

}

If (top!=1)

{

Bt=s [top -];

Cout & lt;
Bt=bt - & gt; Rchild;

}

}

}

Void BiTree: : PostOrder BiNode * (bt)

{

If (bt==NULL) return;

The else

{

PostOrder (bt - & gt; Lchild);

PostOrder (bt - & gt; Rchild);

Cout & lt;
}

}

Int main ()

{

BiTree Test;

Cout & lt; <"The PreOrder is:" & lt;
Test. The Pre ();

Cout & lt;
Test. In ();

Cout & lt;
Test. The Psot ();

return 0;

}

  • Related