Brief introduction
A tree is a nonlinear structure. The essence of a tree is to connect some nodes from the edge to form a hierarchical structure. The binary tree is a special kind of tree, so that each child node of the tree must be less than or equal to 2. The binary lookup tree is a kind of special two-fork tree. So that all nodes of the left node or the left subtree of each node must be less than this node, the right node must be greater than this node. So as to facilitate efficient search.
Here's how to implement a two-fork lookup tree using C #.
Implementing nodes
A binary lookup tree is a collection of nodes. So first you build the node, as shown in code 1.
The node of the binary lookup tree defines
the data of publicclass node {//node itself publicint;
Left child public Node;
The right child is public.
Publicvoid Displaydata ()
{
Console.Write (data+ "");
}
Code 1. Definition of Node
Building a binary tree
The construction of the binary tree is achieved by inserting elements into the binary tree, and all nodes of the root node are inserted into the left subtree of the roots node, greater than the root node, and the right subtree is inserted. And so on recursively. Insert until location is found. The construction process of the binary lookup tree is actually the insertion process of the node. The C # implementation code is shown in code 2.
Publicvoid Insert (int data) {Node Parent;
Wraps the data that you want to insert INTO node newnode=new nodes ();
Newnode.data=data;
If an empty tree, insert the root node if (rootnode==null) {rootnode=newnode;
//Otherwise find the appropriate leaf node position to insert else {node current = RootNode;
while (true) {parent=current;
if (newnode.data<current.data) {current=current.left;
if (current==null) {parent.left=newnode;
After inserting the leaf, jumps out the circulation break;
} else {current = Current.right;
if (current = = null) {parent.right = NewNode; After inserting the leaf, jumps out the circulation break; }
}
}
}
}
Code 2. Implementing two-fork tree insertion