A source program c ++ that creates a binary tree

Source: Internet
Author: User

Typedef struct Node
{
Int data;
Int degree;
Node * LC;
Node * RC;
} * Btree;
# Include <iostream>
# Include <fstream>
Btree creat_btree (char * filename );
Void inordertree (btree L );
Void midordertree (btree L );
Void postordertree (btree L );
Int depth (btree L );
Using namespace STD;
/*************************************** **********/
Int main (INT argc, char * argv [])
{
// System ("type btree. cpp"); // print the source file
Btree jjj = creat_btree ("data.txt"); // non-recursive Binary Tree Generation
If (jjj)
{
Cout <"non-recursive binary tree/N ";
Cout <"Forward traversal :";
Inordertree (jjj );
}
System ("pause ");
Return 0;
}
* ********************** Creat a btree ************* **********/
Btree creat_btree (char * filename)
{
Fstream in (filename );
If (! In)
{
Cout <"file open fail! ";
Return NULL;
}
Btree root = new node;
Root-> lc = root-> rc = NULL;
Int key (0 );
// While the file not empty, go on reading data from File
If (in> root-> data)
{
While (in> key)
{
Btree S = new node;
S-> lc = s-> rc = NULL;
S-> DATA = key;
S-> degree = 0;
Btree P = root;
Bool flag = true;
While (p-> RC | p-> Lc)
{
While (p-> DATA> key & P-> Lc) P = p-> lC;
If (p-> DATA> key)
{
P-> lc = s;
Flag = false;
Break;
}

While (p-> data <key & P-> RC) P = p-> RC;
If (p-> data <key)
{
P-> rc = s;
Flag = false;
Break;
}

If (p-> DATA = Key) {flag = false; P-> degree ++; break ;}
}
If (FLAG)
If (p-> data <key) P-> rc = s;
Else p-> lc = s;
}
Return root;
}
Else {cout <"file open but was empty! "; Return NULL ;}
}
/*************************************** ****/

Void inordertree (btree T)
{
Btree * stack = new btree [50];
Int Top = 0;
Btree P = T;
While (p | top> 0)
{
While (P)
{
Stack [Top] = P;
Top ++;
Cout <p-> data <"; // first visit
P = p-> lC;
}
If (top> 0)
{
Top --;
P = stack [Top];
// Cout <p-> data <""; // mid visit
P = p-> RC;
}
}
Cout <Endl;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.