# Application of tree

## Storage structure of tree

##### Parental representation (sequential storage)

Definition: in each node, the “pointer” (position subscript) pointing to the parents is saved. The root node is fixedly stored in 0, – 1 indicates that there are no parents.

Add: add directly without following the logical order.

Delete: ① set the pointer to – 1. (empty data leads to slower traversal) ② move the last node to the location of the node to be deleted.

Advantages: it is convenient to find the parents of the specified node.

Disadvantages: the child who finds the specified node can only traverse from the beginning.

The node number of the binary tree should correspond to the complete binary tree., The node number reflects the storage location and the logical relationship between nodes.

```
//Maximum number of nodes in the tree
#define MAX_TREE_SIZE 100
//Tree node definition
typedef struct{
ELemType data;
int parent;
}PTNode
//Tree type definition
typedef struct{
PTNode nodes[MAX_TREE_SIZE];
int n;
}PTree;
```

##### Child representation (sequential + chained storage)

Definition: each node is stored in sequence, and the chain header pointer of the child node is saved in each node. The child nodes of each node are linked with a single linked list to form a linear structure.

Advantages: looking for children

Disadvantages: finding parent nodes requires traversing the N child linked lists pointed to by the child linked list pointer field in N nodes.

```
struct CTNode{
//The position of the child node in the array
int child;
//Next child
struct CTNode *next;
};
typedef struct{
ElemType data;
struct CTNode *firstChild;
}
```

##### Child brother notation (chained storage)

Tree and binary tree are converted to each other. A tree represented by a binary list.

Left pointer: first child node

Right pointer: sibling node of child node

`//Tree storage`

##### Transformation between forest and binary tree

Left pointer: child node

Right pointer: sibling node

Use a binary linked list to store the forest. The root node of each tree in the forest is regarded as brotherhood.

## Traversal of trees and forests

#### Tree traversal

###### Root first traversal (depth first search DFS)

The pre root traversal sequence of the tree is the same as that of the corresponding binary tree of the tree.

If the tree is not empty, first visit the root node, and then traverse each subtree in turn.

###### Post root traversal (depth first search DFS)

The back root traversal sequence of the tree is the same as the middle order sequence of the corresponding binary tree of the tree.

If the tree is not empty, first traverse each subtree in turn, and then access the root node.

###### level traversal

Implemented with queue (breadth first search BFS)

① If the tree is not empty, the root node will join the queue

② If the queue is not empty, the queue header element is out of the queue and accessed, and the children of the element are joined in the queue in turn

Repeat ② until the queue is empty.

#### Forest traversal

A set of M (m ≥ 0) disjoint trees. After removing the root node of each tree, its sub trees form a forest.

###### Preorder traversal

If the forest is not empty, then

① Access the root node of the first tree in the forest.

② First traverse the subtree forest of the root node in the first tree

③ The forest formed by traversing the first tree first and then the remaining trees

It is equivalent to first root traversal of each tree in turn.

The forest is transformed into a binary tree, and the binary tree is traversed first.

###### Medium order traversal

If the forest is not empty, then

① A subtree forest that traverses the root node of the first subtree in the forest in medium order

② Access the root node of the first tree

③ The middle order traverses the forest composed of the remaining trees after removing the first tree

The effect is equivalent to post root traversal of each tree in turn.

The forest is transformed into a binary tree, and the binary tree is traversed in middle order.

tree | forest | Binary tree |
---|---|---|

preorder traversal | Preorder traversal | Preorder traversal |

Post root traversal | Medium order traversal | Medium order traversal |

## Binary sort tree

### definition

Binary search tree (BST binary search tree)

A binary tree is either an empty binary tree or a binary tree with the following properties:

① The keywords of all nodes on the left subtree are less than those of the root node;

② The keywords of all nodes on the right subtree are greater than those of the root node.

③ The left subtree and the right subtree are each a binary tree.

**Left subtree node value**

Through the middle order traversal, you can get an increasing ordered sequence.

Binary sort tree can be used for orderly organization and search of elements.

By default, two nodes are not allowed to have the same keyword.

### operation

#### structure

Different keyword sequences may get the same binary sort tree.

The first is the root node, and the subsequent keywords are greater than the right insertion of the node and less than the left insertion of the node.

```
//Establish a binary sort tree according to the keywords in str []
void Creat_BST(BSTree &T,int str[],int n){
T=NULL;
int i=0;
//Insert each keyword into the binary sort tree in turn
while(i
```

#### lookup

**Left subtree node value**

① If the tree is not empty, the target value is compared with the value of the root node.

(1) If equal, the search is successful

(2) If it is less than the root node, it will be found in the left subtree

(3) If it is larger than the root node, it will be found on the right subtree

⑤ Node pointer returned after successful search

⑥ The lookup failed and returned null

```
//Find the node with the value of key in binary sort tree species
//Worst space complexity O (1)
BSTNode *BST_Search(BSTree T,int key){
//If the tree is empty or equal to the node value, the loop ends
while(T!=NULL&&key!=T->key){
//If less than, search on the left subtree
if(keykey)
T=T->lchild;
//If greater than, search on the right subtree
else T=T->rchild;
}
return T;
}
//Recursive implementation
//Worst space complexity O (H)
BSTNode *BST_Search(BSTree T,int key){
if(T==NULL)
return NULL;
if(key == T->key)
return T;
else if(key < T->key)
return BSTSearch(T->lchild,key);
else
return BSTSearch(T->rchild,key);
}
```

#### insert

The position that should be inserted must be the leaf node. Pay attention to modifying its parent node pointer

```
//Insert a new node with keyword K into the binary sort tree (recursive implementation)
int BST_Insert(BSTree &T,int k){
if(T==NULL){
//The newly inserted node is the root node
T=(BSTree)malloc(sizeof(BSTNode));
T->key=k;
T->lchild=T->rchild=NULL;
return 1;
}
else if(k==T->key)
return 0;
else if(kkey)
return BST_Insert(T->lchild,k);
else
return BST_Insert(T->rchild,k);
}
```

#### Search efficiency analysis

Search length: the number of times a keyword needs to be compared.

It reflects the time complexity of the lookup operation.

**Average lookup length (ASL)**）

In the search operation, each node needs to compare the sum of the number of keywords and the ratio of the number of keywords.

The shorter the tree, the fewer searches.

###### Search succeeded

If the tree height is h, the lowest node needs to be compared n times.

Best case: the minimum height of a binary tree with n nodes is [(log2) n] + 1, and the average search length = O ((log2) n)

Worst case: each node has only one branch, tree height h = number of nodes n, average search length = O (n)

###### Search failed

Failed nodes need to be supplemented.

#### delete

Always ensure: left subtree node value

Through the middle order traversal, you can get an increasing ordered sequence.

The deleted node Z is:

###### leaf

It will not destroy the nature of the binary sort tree.

###### There is only one left subtree or right subtree

Then let the subtree of Z become the subtree of the parent node of Z, instead of the position of Z.

###### There are two subtrees on the left and right

Then, the direct successor (or direct precursor) of Z is replaced by Z, and then the direct successor (or direct precursor) is deleted from the binary sort tree, which is converted to the first or second case.

Precursor: the lowest right node in the left subtree.

Successor: the lowest left node in the right subtree.

## balanced binary tree

### definition

Balanced tree (AVL tree), the height difference between the left subtree and the right subtree of any node of the tree shall not exceed 1.

Node balance factor = left subtree height – right subtree height.

A balanced binary tree is a binary sort tree.

### nature

The value of the balance factor of a balanced binary tree node can only be – 1, 0 or 1.

As long as the absolute value of the balance factor of any node is greater than 1, it is not a balanced binary tree.

### balance

In a binary sort tree**insert**How to create a new node**balance**：

Find the first unbalanced node back from the insertion point and adjust the subtree with this node as the root.

The object of each adjustment is**Minimum unbalanced subtree**。 In the insertion operation, as long as the minimum unbalanced subtree is adjusted to balance, other ancestor nodes will restore balance.

#### Minimum unbalanced subtree

To one**balanced binary tree**(all referred to herein)“**Balanced binary sort tree**”）Insert a new leaf node, traverse each ancestor node of the insertion point from bottom to top, and record the first traversed leaf node**|Balance factor | ≥ 2**(i.e**out-off-balance**）The ancestor node of the tree, and the subtree with the node as the root node is the ancestor node of the tree**Minimum unbalanced subtree**。

#### Adjust minimum unbalanced subtree a

It is assumed that the height of all subtrees is h (only h is allowed).

Objectives: ① restore balance ② maintain the characteristics of binary sort tree.

For the convenience of discussion, we use two consecutive letters to represent the balance factor to represent various situations. The first letter represents the balance factor of the root node of the minimum unbalanced subtree, and the second letter represents the balance factor of the root node of the higher subtree of the minimum unbalanced subtree.

###### LL

Inserting in the left subtree of a’s left child leads to imbalance.

Balanced rotation (right single rotation).

The right subtree of the unbalanced subtree is rotated.

Because a new node is inserted into the left subtree (L) of the left child (L) of node a, the balance factor of a increases from 1 to 2, resulting in the loss of balance of the subtree with a as the root, which requires a right rotation operation. Rotate the left child B of a to the right to replace a as the root node, rotate node a to the right and down to become the root node of the right subtree of B, and the original right subtree of B is the left subtree of node a.

###### RR

Insertion in the right child of a causes imbalance.

Left single rotation.

The left child of the unbalanced subtree is rotated.

Because a new node is inserted into the right subtree of the right child of node a, the balance factor of a increases from 1 to 2, resulting in the loss of balance of the subtree with a as the root, requiring a left rotation operation. Rotate the right child B of a to the left to replace a as the root node, rotate node a to the left and down to become the root node of the left subtree of B, and the original left subtree of B is the right subtree of node a.

###### LR

Insertion in the left child of a leads to imbalance.

First left and then right double rotation.

As a new node is inserted into the right subtree of the left child of a, the balance factor of a increases from 1 to 2, resulting in the loss of balance of the subtree with a as the root. It is necessary to rotate twice, first left and then right. First, rotate the root node C of the left child B’s right subtree of node a to the left and lift it to the position of node B, and then rotate the C node to the right and lift it to the position of node a.

Splitting the right subtree of B and inserting a new node into the right subtree of B is equivalent to inserting a new node into the right subtree of C.

###### RL

Inserting in the left subtree of the right child of a causes imbalance