/ * TWOTREE.CPP
Compile in C environment!
Create a binary tree ---> Load data,
----> Traverse ---> Display ---> Destruction *
Both resembling recursive achievement, non-recursion, not familiar, so
* /
#include
#ifndef debug
#define debug
TypedEf int Dattype;
Typedef struct node
{
DataType Data;
Struct Node * LCHILD;
Struct Node * rchild;
} Node;
/ * Tree data structure * /
/
Node * initiate ()
/ * Initialized to empty tree * /
{
Node * root = 0;
Return root;
}
Node * Creat (Datatype Data)
/ * Building node * /
{
Node * TEMP = New Node;
Temp -> Data = DATA;
Temp -> LCHILD = 0;
Temp -> rchild = 0;
Return Temp;
}
/ ******************************************************** /
Void Insert (Node * & root, DataType Data)
// Don't this be like this, Node * & root
/ * Extreme Demoniration Fifty loading data, left sub-tree { Node * p = Creat (data); IF (! root) { Root = P; } Else IF (P-> Data { INSERT (root-> lchild, p-> DATA); } Else { INSERT (root-> rchild, p-> data); } / * Equal will load data to the right child * / } / ************************************************** *** / Void Printtree (Node * root) / * Recursive order traversal ---> Show from small to large * / { IF (! root) return; PRINTTREE (root-> lchild); COUT << root-> data <<: "; PRINTTREE (root-> rchild); Return; } / ************************************************** ******** / Void Freetree (Node * root) { IF (! root) return; Freetree (root -> lchild); Freetree (root -> rchild); Delete root; / / The node is finally deleted! } #ENDIF Debug /// Test code void main () { Int a; Node * root = initiate (); Cout << "-1 to exit:" << Endl; CIN >> A; While (A! = -1) && cin.good ()) // encounter illegal inputs and exit cycles { INSERT (root, a); CIN >> A; } IF (! cin.good ()) // Output error message { Cout << "The Type is Error!" << endl;} PRINTTREE (root); COUT << "OK?" << Endl; Freetree (root); // Destroy the tree to prevent memory leakage Return; }