1. Tree Definition
A Tree is a finite set of n (n ≥ 0) data elements of the same type. The Data Element in the tree is called a Node ). A Tree with n = 0 is called an Empty Tree. For any non-Empty Tree with n> 0, T has:
(1) There is only one special node called the Root node of the tree, and the Root has no parent node;
(2) If n> 1, the other nodes except the root node are divided into m (m> 0) sets that do not match each other.
T1, T2 ,..., Tm, where each set of Ti (1 ≤ I ≤ m) itself is a tree. Tree T1, T2 ,..., Tm
A Subtree ).
From the definition of the tree, we can see that the definition of the tree is recursive, and the tree is used to define the tree. Therefore, the tree (and binary
Many algorithms use recursion.
The Tree form is defined as: Tree is a binary group,
T = (D, R)
Where: D is a finite set of nodes;
R is a finite set of relationships between nodes.
2. Related Terms of the tree:
1. Node: indicates the data element in the tree, which is a relational group between data items and data elements.
. As shown in Figure 5.1, there are 10 nodes in total.
2. Degree of Node ):Number of Subtrees owned by nodes, In Figure 5.1
The degree of Point A is 3.
3. Degree of Tree ):Maximum node degree in the tree. In Figure 5.1, the degree of the tree is
3.
4. Leaf Node: A Node with a degree of 0, also called a terminal Node. In Figure 5.1
Point E, F, G, H, I, and J are all leaf nodes.
5. Branch Node: A Node with a degree of less than 0. It is also called a non-terminal Node or an internal Node.
In Figure 5.1, node A, B, C, and D are branch nodes.
6. Child: the root of the tree. In Figure 5.1, Node B, C, and D are
Child.
7. Parent: the upper node of a node is the Parent node of the node. In Figure 5.1, Node B, C,
The parent node of D is node.
8. Ancestor: All nodes from the root node to the branch on which the node passes. In Figure 5.1
The ancestor of point E is A and B.
9. Descendant (Descendant): Any node in the subtree with a node as the root. In Figure 5.1
All nodes except A are descendants of.
10. Brother: children of the same parent. In Figure 5.1, Node B, C, and D are mutual brothers.
11. Level of Node: the branch from the root Node to the path of a Node in the tree
The number is the hierarchy of the node. The level of the root node is defined as 1, and the level of the other nodes is equal to the level of the parent node plus 1.
12. Cousin (Sibling): the two sides of the same layer have different nodes. In Figure 5.1, G and H interact with each other
Cousin.
13. Depth of Tree: the maximum number of layers of nodes in the Tree. In Figure 5.1, the depth of the tree
Degree is 3.
14. Unordered Tree: Order Structure between child nodes of any node in the Tree
Into irrelevant trees. A tree usually refers to an unordered tree.
15. Ordered Tree: each child node of any node in the Tree is strictly Ordered.
. A binary tree is an Ordered Tree, because each child node in the binary tree is exactly defined as the left of the node.
The child node or the right child node.
16. Forest (Forest): a set of m (m ≥ 0) trees. The concepts of trees and forests in nature are very different.
Big, but in the data structure, the concept of tree and forest is very small. According to the definition, a tree has a root node and
If the root node of the tree is deleted, the tree becomes a forest containing the m tree. Of course, Root
It is defined that a tree can also be called a forest.
Iii. Fundamental Tree operations
1. Root (): Find the Root node of the tree. If the fruit tree is not empty, return the Root node; otherwise, return null;
2. Parent (t): calculates the Parent node of node t. If the parent node of t exists, the parent node is returned,
Otherwise, null is returned;
3. Child (t, I): calculates the I subnode of node t. If yes, the I subnode is returned. No
Null is returned;
4. RightSibling (t): Calculate the first right brother node of node t. If yes, return the first
The right sibling node; otherwise, null is returned;
5. Insert (s, t, I): Insert tree s into the tree as the I subtree of node t. Returns true if the call is successful,
Otherwise, false is returned;
6. Delete (t, I): Delete the I subtree of node t. Return the root node of the I subtree. No
Null is returned;
7. Traverse (TraverseType): Traverse the tree in some way;
8. Clear (): Clear the tree;
9. IsEmpty (): determines whether the tree is an empty tree. If it is an empty tree, true is returned; otherwise, false is returned;
10. GetDepth (): Evaluate the depth of the tree. If the fruit tree is not empty, the hierarchy of the tree is returned; otherwise, 0 is returned.
Iv. Binary Tree Definition
- Binary Tree is a finite set of n (n ≥ 0) nodes of the same type. N = 0 Binary Tree
Empty Binary Tree. For any non-Empty Binary Tree with n> 0:
(1) There is only one special node called the Root node of a binary tree.
Point;
(2) If n> 1, the other nodes except the root node are divided into two sets of different TL,
TR, and TL and TR are itself a binary tree called the Left Subtree)
And Right Subtree ).
Binary Tree is a Binary group,
BT = (D, R)
Where: D is a finite set of nodes;
R is a finite set of relationships between nodes.
According to the definition of the tree, a binary tree is another tree structure and is an ordered tree. Its left subtree
There is a strict order with the right subtree. If the left and right subtree are reversed, it becomes another different binary tree.
- There are five types of Binary Trees: Empty Binary Tree, binary tree with only root nodes, and binary tree with no right subtree
A binary tree with left subtree null and a non-empty binary tree with left and right subtree.
- Full Binary Tree: If a Binary Tree has only 2 knots and degrees of 0
And the node with the degree of 0 is on the same layer, then this binary tree is full Binary Tree, 5.7 ()
. According to the definition, for a full binary tree with a depth of k, the number of nodes is 2k-1.
- Complete Binary Tree (Complete Binary Tree): a Binary Tree with a depth of k and n nodes. if and only when each node has a depth of k, A full binary tree with n knots numbered from 1 to n is called a full binary tree, as shown in 5.7 (B. The full Binary Tree feature that the leaf node can only appear on the maximum two layers of the hierarchy, in addition, the maximum level of the child of the left branch of a node is equal to or greater than 1 of the child of the right branch.
- Binary tree traversal:
A) binary tree traversal refers to accessing each node in a binary tree in a certain order, so that each node is accessed
Once and only once. Traversal is a common operation in Binary Trees, because in actual applications,
It is often required to process one or some specific nodes in a binary tree. You need to first find this or
Nodes.
B) In fact, traversal changes the node information in a binary tree from non-linear arrangement to linear
. That is to say, traversal operations make the nonlinear structure linear.
C) according to the definition of a binary tree, a binary tree consists of three parts: root node, left subtree, and right subtree,
If it is specified that D, L, and R represent traversing the root node, the left subtree, And the right subtree
There are 6 traversal methods: DLR, DRL, LDR, LRD, RDL, and RLD. Since the left subtree and
Traversing the right subtree first has no essential difference in algorithm design. Therefore, we only discuss three methods: DLR (First Order
(Traversal), LDR (middle-order traversal), and LRD (post-order traversal ).
D) In addition to the three traversal methods, there is also a method: Level Order ). Sequence Traversal
Is to access each node only once from the root node in the order of top to bottom and left to right.
Since the tree definition is recursive, The traversal algorithm also uses recursion. The following sections describe the four
Algorithm
E)The basic idea of sequential traversal is: first access the root node, then traverse its left subtree in sequence, and then traverse its right subtree in sequence.
F)The basic idea of central order traversal is: first traverse the left subtree of the root node in the central order, then access the root node, and finally traverse its right subtree in the middle order.
G)The basic idea of post-order traversal is: first traverse the left subtree of the root node in a descending order, then traverse the right subtree of the root node in a descending order, and finally access the root node.
H)The basic idea of sequence traversal is: Because the sequence of sequence traversal nodes is first Accessed at the first node, the sequence of queue operations is the same. Therefore, set a queue during the sequence traversal,Introduce the root node into the queue. When the queue is not empty, perform the following three steps cyclically:
(1)Extracts a node reference from the queue and accesses the node;
(2)If the left subtree of the node is not empty, the left subtree of the node is referenced into the queue;
(3)If the right subtree of the node is not empty, the right subtree of the node is referenced into the queue;
- 6.Specific Code for binary tree implementation (including the establishment of Binary Tree classes and the specific implementation code for the first, middle, and back-order algorithms ):
Using System;
Using System. Collections. Generic;
Using System. Collections;
Class Program
{
Static void Main (String [] args)
{
Node <string> H = new Node <string> ("H", null, null );
Node <string> I = new Node <string> ("I", null, null );
Node <string> J = new Node <string> ("J", null, null );
Node <string> D = new Node <string> ("D", H, I );
Node <string> E = new Node <string> ("E", J, null );
Node <string> B = new Node <string> ("B", D, E );
Node <string> F = new Node <string> ("F", null, null );
Node <string> G = new Node <string> ("G", null, null );
Node <string> C = new Node <string> ("C", F, G );
Node <string> A = new Node <string> ("A", B, C );
Console. WriteLine ("first traverse result set :");
Node <string>. PreOrder ();
Console. WriteLine ("sequential traversal result set :");
Node <string>. InOrder ();
Console. WriteLine ("result set of post-order traversal :");
Node <string>. PostnOrder ();
Console. WriteLine ("sequence traversal result set :");
Node <string>. LevelOrder ();
}
}
// Create a binary tree generic class
Public class Node <T>
{
Private T data; // data domain
Private Node <T> lChild; // left child
Private Node <T> rChild; // right child
// Constructor
Public Node (T val, Node <T> lp, Node <T> rp)
{
Data = val;
LChild = lp;
RChild = rp;
}
// Constructor
Public Node (Node <T> lp, Node <T> rp)
{
Data = default (T );
LChild = lp;
RChild = rp;
} // Constructor
Public Node (T val)
{
Data = val;
LChild = null;
RChild = null;
}
// Constructor
Public Node ()
{
Data = default (T );
LChild = null;
RChild = null;
}
// Data attributes
Public T Data
{
Get
{
Return data;
}
Set
{
Value = data;
}
}
// Left child attributes
Public Node <T> LChild
{
Get
{
Return lChild;
}
Set
{LChild = value;
}
}
// Right child attributes
Public Node <T> RChild
{
Get
{
Return rChild;
}
Set
{
RChild = value;
}
}
Public static void PreOrder (Node <T> root)
{
// The root node is empty.
If (root = null)
{
Return;
}
// Process the root node
Console. WriteLine ("{0}", root. Data );
// First traverse the left subtree
PreOrder (root. lChild );
// First traverse the right subtree
PreOrder (root. rChild );
}
Public static void InOrder (Node <T> root)
{
// The root node is empty.
If (root = null)
{
Return;
}
// Traverse the left subtree in the middle order
InOrder (root. LChild );
Console. WriteLine ("{0}", root. data );
// Traverse the right subtree in the middle order
InOrder (root. rChild );
}
Public static void PostnOrder (Node <T> root)
{
// The root node is empty.
If (root = null)
{
Return;
}
// Traverse the left subtree in descending order
PostnOrder (root. LChild );
// Traverse the right subtree in descending order
PostnOrder (root. rChild );
Console. WriteLine ("{0}", root. data );
}
Public static void LevelOrder (Node <T> root)
{
// The root node is empty.
If (root = null)
{
Return;
}
// Set a node for storing sequence traversal in a queue
CSeqQueue <Node <T> sq = new CSeqQueue <Node <T> (50 );
// Enter the root node
Sq. In (root );
// The queue is not empty and the node is not processed
While (! Sq. IsEmpty ())
{
// Node team-up
Node <T> tmp = sq. Out ();
// Process the current node
Console. WriteLine ("{0}", tmp. data );
// Enter the left child node of the current node
If (tmp. LChild! = Null)
{
Sq. In (tmp. LChild );
}
// Add the right child node of the current node to the queue
If (tmp. RChild! = Null)
{
Sq. In (tmp. RChild );
}
}
}
}
// Queue Interface
Public interface IQueue <T>
{
Int GetLength (); // evaluate the queue length
Bool IsEmpty (); // determines whether the column is empty.
Void Clear (); // Clear the queue
Void In (T item); // enter the team
T Out (); // leaves the team
T GetFront (); // get the first element
}
// Queue generic instance
Public class CSeqQueue <T>: IQueue <T> {
Private int maxsize; // The capacity of the cyclic sequence queue.
Private T [] data; // array, used to store data elements in the cyclic sequence queue
Private int front; // indicates the head of the cyclic ordered queue.
Private int rear; // indicates the end of the cyclic order queue.
// Indexer
Public T this [int index]
{
Get
{
Return data [index];
}
Set
{
Data [index] = value;
}
}
// Capacity attribute
Public int Maxsize
{
Get
{
Return maxsize;
}
Set
{
Maxsize = value;
}
}
// Queue header attributes
Public int Front
{
Get
{
Return front;
}
Set
{
Front = value;
}
}
// Team-end attributes
Public int Rear
{
Get
{
Return rear;
}
Set
{
Rear = value;
}
}
// Constructor
Public CSeqQueue (int size)
{
Data = new T [size];
Maxsize = size;
Front = rear =-1;
}
// Calculate the length of the cyclic ordered queue
Public int GetLength ()
{
Return (rear-front + maxsize) % maxsize;
}
// Clear the cyclic sequence queue
Public void Clear ()
{
Front = rear =-1;
}
// Determine whether the cyclic sequence queue is empty
Public bool IsEmpty ()
{
If (front = rear)
{
Return true;
}
Else
{
Return false;
}
}
// Determine whether the cyclic sequence queue is full
Public bool IsFull ()
{
If (rear + 1) % maxsize = front)
{
Return true;
}
Else
{
Return false;
}
}
// Enter the team
Public void In (T item)
{
If (IsFull ())
{
Console. WriteLine ("Queue is full ");
Return;
}
Data [++ rear] = item;
}
// Team out
Public T Out ()
{
T tmp = default (T );
If (IsEmpty ())
{
Console. WriteLine ("Queue is empty ");
Return tmp;
}
Tmp = data [++ front];
Return tmp;
}
// Obtain the data element of the queue Header
Public T GetFront ()
{
If (IsEmpty ())
{
Console. WriteLine ("Queue is empty! ");
Return default (T );
}
Return data [front + 1];
}
- } Tree to binary tree
The binary tree is ordered. To avoid confusion, we specify each knot in the unordered tree.
The child node of the vertex is numbered from left to right. For the tree shown in 5.1, the root node A has three
Child B, C, and D. It is required that node B is the first child of node A, and node C is 2nd of node.
Child, node D is the 3rd child of node.
To convert a tree to a binary tree, follow these steps:
(1) wire. Adds a line between all the sibling nodes;
(2) strip. Is to keep the connection between each node in the tree and the first child node.
Line to delete the line between it and other child nodes;
(3) rotate. It is to take the root node of the tree as the axis, and rotate the entire tree clockwise for a certain angle, so that
The structure is layered.
- Binary tree to tree
The process of converting a binary tree to a tree is the inverse process of converting a tree to a binary tree. The steps are as follows:
(1) If the left child node of a node exists, place the right child node of the left child node and the right child node of the right child node ...... Are used as the child node of the node, and connect the node with these right child nodes using a line;
(2) Delete the connections between all nodes in the original binary tree and the right child node;
(3) organize the trees obtained in steps (1) and (2) to make the trees have a clear structure.
Figure 5.17 shows the process of transforming a binary tree into a tree.