# Chapter Six, Tree Learning Notes

Posted by rushdot on Sat, 05 Feb 2022 18:31:22 +0100

Tree: A tree is a finite set of n(n < 0) nodes. n=0 is called an empty tree. In any non-empty tree: (1) there is only one specific node called Root; (2) When n>1, the remaining nodes can be divided into m(m>0) finite disjoint sets.Each of these collections is itself a tree and is called a SubTree of the root.

1. When n > 0, the root node is unique, it is impossible to have more than one root node. Don't mix it with big trees in reality. Trees in reality have many roots. That is a real tree. Trees in data structure can only have one root node.

2. When m>0, there is no limit to the number of subtrees, but they must not intersect each other.

## Node classification:

The number of subtrees a node has is called the degree of the node (Degree). A node with a degree of 0 is called a Leaf or a terminal node. Nodes with degrees other than 0 are referred to as non-terminal or branch nodes. In addition to the root node, the branch node is also known as the internal node. The degree of a tree is the maximum of the degree of each node in the tree.

The Level of a node is defined from the root, which is the first Level and the child of the root is the second Level. The maximum Level of nodes in a tree is called the depth (Depth) or height of the tree, and the tree shown below has a depth of 4.

If the subtrees of nodes in a tree are considered left-to-right sequential and cannot be interchanged, it is called an ordered tree, otherwise it is called an disordered tree.

Forest is a collection of M (m < 0) disjoint trees.

Characteristics of Linear and Tree Structures
 linear structure tree structure First data element: no precursors Root node: no parents, only Last Data Element: No Succession Leaf node: childless, can have more than one Intermediate elements: one precursor and one successor Middle node: one parent with more than one child

## The abstract data type of the tree

```ADT Trees ( tree)
Data
A tree is composed of a root node and several sub-trees. Nodes in the tree have the same data type and hierarchical relationship.
Operation
InitTree(*T)Construct an empty tree T.
DestoryTree(*T)Destroy Trees T.
CreateTree(*T,definition):Press definition The definition of the tree is given to construct the tree.
ClearTree(*T):If Tree T Exists, then the tree T empty
TreeEmpty(T):if T Empty tree, return True，otherwise false.
TreeDepth(T):Return T Depth of
Root(T):Return T Root node.
Value(T,cur_e):cur_e Is Tree T A node that returns its value
Assign(T,cur_e,value):Give Tree T Of cur_e Node assignment value
Parent(T,cur_e):if cur_e Is Tree T A non-root node returns its parents, otherwise returns null.
LeftChild(T,cur_e):if cur_e Is Tree T A non-leaf node returns its leftmost child, otherwise it returns empty.
InsertChild(*T,*p,i,c):among p Point to Tree T A node of, i For the specified node p Degree plus 1, non-empty tree c and T Disjoint, operation result is insert c For Trees T in p Refers to the number of nodes i A subtree.
DeleteChild(*T,*p,i):among p Point to Tree T A node of, i For the specified node p Degree, the result is delete T in p The first of the indicated nodes i A subtree.

## Storage structure of trees

Parental notation: In each node, an indicator is attached to indicate the location of the parent node in the chain table.

```/*Parent Representation Node Structure Definition for Trees*/
#define MAX_TREE_SIZE 100
typedef int TElemType;    /*The data type of the tree node, currently tentatively integer.
typedef struct PTNode    /*Node structure*/
{
TElemType data;    /*Node data*/
int parent;    /*Parental Position*/
}PTNode;
typedef struct        /*tree structure*/
{
PTNode nodes[MAX_TREE_SIZE]; /*Array of nodes*/
int r，n;
}PTree;```

With this storage structure, we can easily find the parent node of a node based on its parents pointer, and the time complexity is O(1) until the parent is -1, indicating that the root of the tree node has been found. But if we want to know what the children of nodes are, we need to traverse the whole structure (shortcomings).

In addition, this structure can be extended to a parental domain, a first child domain, and a right sibling domain. Storage structure design is a very flexible process. The rationality of a storage structure depends on the appropriateness, convenience and time complexity of the operation based on the storage structure.

Child Representation:

Arrange the child nodes of each node and use a single-chain list as the storage structure, then n nodes have n child chains, and if it is a leaf node, the single-chain list is empty. Then the N header pointers form a linear table, which is stored in a one-dimensional array using a sequential storage structure, as shown below:

There are two structures mentioned in this book, one is the child node of the child chain table, where the child is a data field that stores the subscript of a node in the header array. Next is a pointer field that stores a pointer to the next child node of a node.

The other is the header node of the header array, where data is the data domain that stores the data information of the nodes. First child is the header pointer field that stores the header pointer of the child chain table for that node.

```/*Child Representation Structure Definition of Trees*/
#define MAX_TREE_SIZE 100
typedef struct CTNode /*Child Node*/
{
int child;
struct CTNode *next;
}*ChildPtr;

{
TElemType data;
ChildPtr firstchild;
} CTBox;

typedef struct    /*tree structure*/
{
CTBox nodes[MAX_TREE_SIZE];    /*Array of nodes*/
int r,n;                    /*Root position and number of nodes*/
}CTree;```

## Definition of a binary tree

A Binary Tree is a finite set of n(n < 0) nodes, either an empty set (called an empty Binary Tree), or a Binary Tree consisting of a root node and two disjoint left and right subtrees, respectively, called root nodes.

The characteristics of binary trees:

1. Each node has at most two subtrees, so there are no nodes with a degree greater than 2 in the binary tree.

2. The left subtree and the right subtree are ordered, and the order cannot be reversed arbitrarily.

3. Even if a node in a tree has only one tree, it must be distinguished whether it is a left subtree or a right subtree. (

Binary trees have five basic forms:

1. Empty Binary Tree

2. Only one root node

3. Root node has only left subtree

4. Root node has only right subtree

5. Root node has both left and right subtrees

Special binary trees:

1. Oblique Tree

A binary tree with only the left node for all nodes is called a left diagonal tree. All nodes are just right subtrees of a binary tree called a right diagonal tree. Both are collectively referred to as oblique tree beard.

2. Full Binary Tree

In a binary tree, if all branch nodes have left and right subtrees and all leaves are on the same level, such a binary tree is called a full binary tree.

Features of full binary trees:

1. Leaves can only appear on the lowest level. It is impossible to achieve balance when it appears on other layers.

2. The degree of non-leaf nodes must be 2.

3. Among binary trees of the same depth, the full binary tree has the most nodes and leaves.

3. Complete Binary Tree

A binary tree with n nodes is sequentially numbered. If a node numbered I (1 < I < n) is identical to a node numbered i i n a full binary tree at the same depth i n the binary tree, the binary tree is called a complete binary tree.

A full binary tree must be a full binary tree, but a full binary tree may not be full.

Features of complete binary trees:

1. Leaf nodes can only appear on the bottom two levels.

2. The lowest leaves must be concentrated in the left continuous position.

3, the last two layers, if there are leaf nodes, they must all be in the right continuous position.

4. If the node degree is 1, then the node has only left children, that is, there is no right subtree.

5. A binary tree with the same number of nodes has the smallest depth of a complete binary tree.

## Properties of Binary Trees

Property 1: At most on the level i of a binary treeNodes (i < 1)

Property 2: A binary tree with a depth of k has at mostNodes (k < 1)

Property 3: For any binary tree T, if its terminal node number isThe number of nodes with degree 2 is

be+1.

## Binary Tree Storage Structure

Binary tree lookup storage structure:

Binary Chain List:

Each node of a binary tree has at most two children, so a data field and two pointer fields are designed for it. We call such a list a binary list.

Data is a data field, lchild and rlight are pointer fields, with left and right children's pointers.

```/*Definition of Binary Chain List Node Structure for Binary Trees*/
typedef struct BiTNode    /*Node structure*/
{
TElemType data;        /*Node data*/
struct BiTNode *lchild, *rchild;    /*Left and right child pointer*/
}BiTNode, *BiTree;```

Structure diagram:

## Traversing a Binary Tree

The traversing binary tree refers to accessing all the nodes in the binary tree in a certain order, starting from the root node, so that each node is visited sequentially and only once.

Traversal method for binary trees:

1. Pre-order traversal

The rule is that if the binary tree is empty, the empty operation returns, otherwise the root node is visited first, then the left subtree is traversed in advance, and the right subtree is traversed in advance. The traversal order is as follows: ABDGHCEIF.

2. Intermediate traversal

The rule is that if the binary tree is empty, the empty operation returns, otherwise starting at the root node (note that the root node is not visited first), the left subtree of the root node is traversed in middle order, then the root node is visited, and the right subtree is traversed in middle order. The traversal order is as follows: GDHBAEICF.

3. Post-order traversal

The rule is that if the tree is empty, the empty operation returns, otherwise left-to-right leaves followed by nodes are traversed to access the left and right subtrees, and finally the root node. The following is the traversal order:GHDBIEFCA

4. Sequence traversal

The rule is that if the tree is empty, the empty operation returns, otherwise, the access starts from the upper level of the tree, that is, the root node, traverses from top to bottom, and in the same level, accesses the nodes one by one in left-to-right order. The traversal order is as follows: ABCDEFGHI.

Pre-order traversal algorithm:

```/*Pre-order traversal recursive algorithm for binary trees*/
void PreOrderTraverse(BiTree T)
{
if (T=NULL)
return;
printf("%c",T->data);    /*Display node data, which can be changed to other node operations*/
PreOrderTraverse(T->lchild);    /*Then traverse the left subtree in order*/
PreOrderTraverse(T->rchild);    /*Last traverse right subtree in order*/
}```

Median traversal algorithm:

```/*Recursive algorithm for middle-order traversal of binary trees*/
void InOrderTraverse(BiTree T)
{
if (T=NULL)
return;
InOrderTraverse(T->lchild);    /*Traversing left subtree in middle order*/
printf("%c",T->data);    /*Display node data, which can be changed to other node operations*/
InOrderTraverse(T->rchild);    /*Last traverse right subtree in middle order*/
}```

Post-order traversal algorithm:

```/*Post-order traversal recursive algorithm for binary trees*/
void PostOrderTraverse(BiTree T)
{
if (T=NULL)
return;
PostOrderTraverse(T->lchild);    /*Traversing left subtree sequentially*/
PostOrderTraverse(T->rchild);    /*Traversing the right subtree in a later order*/
printf("%c",T->data);    /*Display node data, which can be changed to other node operations*/
}```

The traversal properties of two binary trees:

1. A binary tree can be uniquely identified with known pre-order and middle-order traversal sequences.

2. A binary tree can be uniquely identified with known post-order and middle-order traversal sequences.

## Establishment of Binary Tree

Assuming that the nodes of a binary tree are all one character, we enter the sequence AB#D##C## one by one with the keyboard.

```/*Enter the values of the nodes in the binary tree in order of precedence (one character)*/
/* #Represents an empty tree, and constructs a binary chain table to represent a binary tree T.*/
void CreateBiTree(BiTree *T)
{
TElemType ch;
scanf("%c",&ch);
if(ch=='#')
*T=NULL;
else
{
*T=(BiTree)malloc(sizeof(BiTNode));
if(!*T)
exit(OVERFLOW);
(*T)->data=ch;    /*Generate Root Node*/
CreateBiTree(&(*T)->lchild);    /*Construct left subtree*/
CreateBiTree(&(*T)->rchild);    /*Construct Right Subtree*/
}
}```

## Tied Binary Tree

We refer to the pointer to the forerunner and the successor as the clue, and the binary chain table with the clue as the clue chain table. The corresponding binary tree is called the Threaded Binary Tree.

Implementing the structure of a threaded binary tree:

```/*Binary Thread Storage Structure Definition for Binary Trees*/
typedef struct BiThrNode        /*Binary Thread Storage Node Structure*/
{
TElemType data;        /*Node data*/
struct BiThrNode *lchild, *rchild;    /*Left and right child pointer*/
PointerTag LTag;
PointerTag RTag;        /*Left and right identification*/
}BiThrNode, *BiThrTree;```

The essence of threading is to change a null pointer in a binary list to a leading or succeeding thread. Since precursor and subsequent information is only available when the binary tree is traversed, threading is the process of modifying the null pointer during traversal.

Intermediate traversal threaded recursive function code:

```BiThrTree pre;    /*Global variable, always pointing to the node you just visited*/
{
if(p)
{
if(!p->lchild)            /*No left child*/
{
p->lchild=pre;        /*Left child pointer to front*/
}
if(!pre->rchild)        /*Progenitor has no right child*/
{
pre->rchild=p;    /*Front right child pointer to next (current node p)*/
}
pre=p;                /*Keep the pre p pointing to the pioneer of p*/
}
}```

## Conversion of Trees, Forests and Binary Trees

The steps for converting a tree to a binary tree are as follows:

1. Wiring up. Add a line between all the brothers.

2. Go online. For each node in the tree, keep only its connection to the first child node, and delete its connection to other child nodes.

3. Level adjustment. With the root node of the tree as the axis, rotate the whole tree clockwise at an angle to make its structure clear. Note that the first child is the left child of the binary tree node, and the brother's converted child is the right child of the node. (

The steps for converting forests to binary trees are as follows:

1. Convert each tree to a binary tree.

2. Lesson 1 The binary tree does not move. Start with the second binary tree, connect the root nodes of the latter binary tree with lines as the right children of the root nodes of the former binary tree. When all the binary trees are joined, they are converted from the forest.

The steps for converting a binary tree to a tree are as follows:

Binary tree conversion is the inverse process of converting a tree to a binary tree.

1. Wiring up. If a left child node of a node exists, the right child node of the left child, the right child node of the right child, and the right child node of the right child are all children of this node. Connect this node with these right child nodes by a line.

2. To disconnect. Delete the links between all nodes in the original binary tree and their right child nodes.

3. Level adjustment. Make it hierarchical.

The steps for converting a binary tree into a forest are as follows:

Whether a binary tree can be converted into a tree or a forest depends on whether the root node of the binary tree has a right child, or if it is a forest, or if it is not, a tree.

1. Starting from the root node, if the right child exists, delete the connection of the right child node, and then look at the separated binary tree. If the right child exists, delete the connection... Until all the right children's connections are deleted, a separate binary tree is obtained.

2. Convert each separated binary tree into a tree.

Topics: data structure