[Cpp]
# Include <iostream>
# Include <stack>
Using namespace std;
// Node
Struct node
{
Node * lchild, * rchild;
Int value;
};
// Binary Search Tree
Class list
{
Public:
List ();
// Here the m_print function is used for recursion. The print function is equivalent to a set
Void print ();
Private:
// Privatize recursive functions
Void m_print (node * p, int value );
Private:
Node * root;
};
Void list: m_print (node * p, int value)
{
// If p is null, return
If (p = NULL)
Return;
// Line and sum
Value + = p-> value;
// Return to the leaf node
If (NULL = p-> lchild & NULL = p-> rchild ){
Cout <value <endl;
Return;
}
// Recursion in the left and right directions
M_print (p-> lchild, value );
M_print (p-> rchild, value );
}
Void list: print ()
{
M_print (root, 0 );
}
List: list ()
{
Cout <"Enter the node you want to enter and press '#' to exit:" <endl;
Int I;
// You can use cin. fail () and cin. bad () to determine whether or not
If (cin> I = NULL ){
Cout <"your input is incorrect" <endl;
Exit (-1 );
}
// Create the root node
Root = new node;
Root-> value = I;
Root-> lchild = NULL;
Root-> rchild = NULL;
// Create two temporary nodes, p open up new nodes, and q is binary search and positioning
Node * p, * q;
While (cin> I! = NULL ){
// Create a new node
P = new node;
P-> value = I;
P-> lchild = NULL;
P-> rchild = NULL;
// The binary search tree starts from q = root. If it is small, it turns to left, and if it is large, it turns to right. If it has a position, it is inserted.
Q = root;
While (1 ){
// The inserted node is smaller than the Compare value of the node. If the left node is empty, the inserted node is inserted. Otherwise, q = q-> lchild continues to judge.
If (p-> value <q-> value ){
If (q-> lchild)
Q = q-> lchild;
Else {
Q-> lchild = p;
Break;
}
}
// The inserted node is greater than the Compare value of the node. If the right node is empty, the inserted node is inserted. Otherwise, q = q-> rchild continues to judge.
Else if (p-> value> q-> value ){
If (q-> rchild)
Q = q-> rchild;
Else {
Q-> rchild = p;
Break;
}
}
// If the two nodes are equal, exit the program directly (somewhat violent)
Else {
Cout <"node repeated !! "<Endl;
Exit (-1 );
}
}
}
}
Void main ()
{
List test;
// The print function prints the length of all root nodes to all leaf nodes.
Test. print ();
System ("pause ");
}