[SinGuLaRiTy] Balance Tree, singularity Balance Tree

Source: Internet
Author: User

[SinGuLaRiTy] Balance Tree, singularity Balance Tree

[SinGuLaRiTy-1009] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved.

A binary search tree is a non-empty Binary Tree of the following nature:

(1) If the left subtree of the root node is not empty, all node values of the Left subtree are smaller than the root node values;

(2) If the right subtree of the root node is not empty, the value of all nodes in the right subtree is not smaller than the value of the root node;

(3) The left and right trees of the root node are also binary sorting trees;

Obviously, you can traverse the binary tree in the middle order to obtain the sequence of ascending node values.

Eg. is a binary search tree:

The sequential traversal is, 39, and.

 

Build code
Const int MAXN = 101; struct node {int data; // keyword int lch, rch; // left and right sub-pointer}; node bst [MAXN]; // Binary Search Tree int n; void init () // read data {int I, t, r = 0; cin> n; for (I = 1; I <= n; I ++) {cin> t; insert (r, t); // insert t into the tree where r is the root. }}
Insert operation
void insert(int &root,int t){   if(root==0)      {bst[cnt++].data=t;       root=cnt;        return;      }if(t<bst[root].data) insert(bst[root].lch,t);else if(t>bst[root].data) insert(bst[root].rch,t);}
Search operation

Find

int find(int root,int x){    if(x==bst[root].data)return root;    if(root==0)return -1;    if(x>bst[root].data)     return find(bst[root].rch,x);    else     return find(bst[root].lch,x);}

If the node is found, the subscript of the node is returned; otherwise,-1 is returned.

Delete operation

If the node is found, the node is deleted. If the node is not found, nothing is done.

The delete operation is somewhat complicated. Let's analyze it first: If the deleted node is a leaf node, delete it directly.

If the deleted node only has a left son or a right son, delete the node directly and connect the father and son of the node, similar to the delete of the linked list.

What should I do if the deleted node has a left or right son? You can set this node to x. Find the largest node t in the left subtree of x, execute: bst [x]. data = bst [t]. data; and delete t.

void delete(int &root,int vx){   if(root==0)return;   if(bst[root].data>vx)      delete(bst[root].lc,vx);   else if(bst[root].data<vx)     delete(bst[root].rc,vx);   else     {        if(bst[root].lch==0||bst[root].rch==0)        root=bst[root].lch+bst[root].rch;        else        {         int t=bst[root].lch;         int f=root;           while(t.rch)              {                 f=t;                t=bst[t].rch;             }             bst[root].data=bst[t].data;            if(f==root)bst[f].lch=bst[t].lch;               else bst[f].rch=bst[t].lch;        }   }}
Inert Deletion

In fact, the delete operation can be roughly processed. That is, only the nodes to be deleted are marked and not deleted. This is much easier. Efficiency has little impact: if few nodes are deleted, they will not be affected at all. Even if many nodes are deleted, the time complexity will not be increased, but the constant will increase.

 

It can be seen that, under ideal conditions, the time complexity of insert, find, delete, and other operations in binary search is O (logN ). However, if fruit tree degradation is called a chain, the time complexity of insert, find, delete, and other operations is O (N.

We can make some improvements to the tree so that in the worst case, the operations of the Binary Search count can also achieve the time complexity of O (logN, now we have the AVL (Balance Tree) to talk about ).

Balancing tree Definition

Balanced Tree: the Tree with the O (logn) height.

Balanced Binary Tree: it was first proposed by Adelson-Velskii and Landis in 1962 and is also called AVL Tree.

If T is a non-empty Binary Search Tree, TL and TR are its left subtree and right subtree respectively, T is an AVL tree when T meets the following conditions:

1) TL and TR are AVL trees;

2) | hL-hR | ≤ 1. hL and hR are the heights of left and right subtree, respectively.

(The empty binary tree is also an AVL Tree)

Highly balanced binary search tree

 

 

Highly unbalanced Binary Search Tree

 

 

Features required by the AVL Tree

The AVL tree height of n elements is O (logn );

The AVL Search Tree of an nelement can be searched within the O (height) = O (logn) time;

Insert a new element into an AVL Search Tree of an nelement to obtain an AVL Tree with n + 1 elements. This insertion process can be completed within O (logn) time;

Delete an element from the AVL Search Tree of an nelement to obtain an AVL Tree of N-1 elements. This deletion process can be completed within O (logn) time.

AVL Tree Height

Assume that Nh is the minimum number of nodes in an AVL tree with a height of h.

 

We can see that the definition of Nh is very similar to that of the Fibonacci series.

 

 

AVL Tree balance factor

Add a balance factor bf for each node. The equilibrium factor bf (x) of node x is defined as bf (x) = hL-hR. That is, the height of the Left subtree of x-the height of the right subtree of x.

From the definition of the AVL Tree, we can know that the possible values of the equilibrium factor are-1, 0, and 1.

Int zig (int r) // right-hand {int t = tree [r]. lc; tree [r]. lc = tree [t]. rc; tree [t]. rc = r; tree [r]. h = max (tree [tree [r]. rc]. h, tree [tree [r]. lc]. h) + 1; tree [t]. h = max (tree [tree [t]. rc]. h, tree [tree [t]. lc]. h) + 1; return t;} // Note: Assume that r must have the left son. After the right hand, t becomes the root node.

 

Zag rotation: counterclockwise

 

Insert A new node into the right subtree E. If the height of the subtree increases by 1, the balance factor of node A becomes-2, and an imbalance occurs.

Check three nodes A, C, and E along the insert path. They are in a straight line in the direction of "\" and need to be rotated by zag.

Take node C as the rotation axis, let node A rotate to the left child of C, C replaces the original position of A, the original left child of c d to the right child of.

Left Single Rotation Algorithm
Int zag (int r) // left {int t = tree [r]. rc; tree [r]. rc = tree [t]. lc; tree [t]. lc = r; tree [r]. h = max (tree [tree [r]. rc]. h, tree [tree [r]. lc]. h) + 1; tree [t]. h = max (tree [tree [t]. rc]. h, tree [tree [t]. lc]. h) + 1; return t;} // Note: r must have the right son.

 

Zagzig rotation: First left and then right

Insert a new node into the subtree F or G, and the height of the subtree increases by 1. The balance factor of node A is changed to 2, and an imbalance occurs.

Select three nodes A, B, and E from node A along the insert path. They are located on A line such as "". Therefore, you need to perform double rotation first, left, and right.

First, take node E as the rotation axis, and rotate Node B counter-clockwise. Take the E generation as the original position of B for zag rotation.

Take node E as the rotation axis, rotate node A clockwise, and perform zig rotation to make it balanced.

 

 

Zagzig Rotation Algorithm
Int zagzig (int r) // double rotation of the Left subtree {tree [r]. lc = zag (tree [r]. lc); return zig (r );}
Zigzag rotation: First right and then left double Rotation

 

The left and right sides of the image are rotated on both sides of the image.

Insert a new node into the subtree F or G. The height of the subtree increases by 1. The balance factor of node A changes to-2, and an imbalance occurs.

Select three nodes A, C, and D from node A along the insert path. They are located on A line such as ">" and need to be rotated first, right, and left.

Perform LL rotation first: Rotate node C clockwise with node D as the rotation axis, and replace the original C position with D.

RR rotation: Rotate node A against the clockwise side of node D to restore the tree balance.

Zigzag Rotation Algorithm
Int zigzag (int r) // The right subtree is rotated twice {tree [r]. rc = zig (tree [r]. rc); return zag (r );}
Create an AVL Tree

Starting from an empty tree, you can enter key values of a series of objects to gradually establish an AVL Tree. when inserting a new node, you can use the preceding algorithm to perform a balanced rotation.

For example, the input key value sequence is {16, 3, 7, 11, 9, 26, 18, 14, 15} to construct an AVL Tree.

 

 

 

 

 

 

Insert operation code
Int insert (int x, int r) {if (r = 0) // to the leaf node, {tree [++ cnt]. v = x; tree [cnt]. h = 1; return cnt;} if (x <tree [r]. v) // case 1 or case 2 {tree [r]. lc = insert (x, tree [r]. lc); if (tree [tree [r]. lc]. h = tree [tree [r]. rc]. h + 2) {if (x <tree [tree [r]. lc]. v) r = zig (r); // case 1 else if (x> tree [tree [r]. lc]. v) r = zagzig (r); // case 2} else if (x> tree [r]. v) // case 3 or case 4 {tree [r]. rc = insert (x, tree [r]. rc); if (tree [tree [r]. rc]. h = tree [tree [r]. lc]. h + 2) {if (x> tree [tree [r]. rc]. v) r = zag (r); // case 4 else if (x <tree [tree [r]. rc]. v) r = zigzag (r); // case 3} tree [r]. h = max (tree [tree [r]. lc]. h, tree [tree [r]. rc]. h) + 1; return r ;}

 

AVL tree deletion

The delete operation is similar to the delete operation of the common binary lookup count. The difference is that it needs to be adjusted after deletion.

Case 1: if the current node is a leaf node, delete it directly.

Case 2: If the current node has only one son, connect the son to the father, similar to deleting a node in the linked list.

Case 3: if the current node has a left and right son, extract the largest node x from the left son, use its value to replace the node to be deleted, and then delete node x.

Start from the deleted node (Case 3 starts from x and goes up until the root node ).

Delete Code
Int dele (int & r, int x) // Delete x from the Child tree of r. Note that if no x exists, delete {int tx; if (x = tree [r]. v | (x <tree [r]. v & tree [r]. lc = 0) | (x> tree [r]. v & tree [r]. rc = 0) {if (tree [r]. lc = 0 | tree [r]. rc = 0) {tx = tree [r]. v; r = tree [r]. lc + tree [r]. rc; return tx;} else tree [r]. v = dele (tree [r]. lc, x);} else {if (x <tree [r]. v) tx = dele (tree [r]. lc, x); else tx = dele (tree [r]. rc, x);} maintain (r); return tx ;}
Adjustment
Void maintain (int & r) // adjust the subtree whose r is the root {if (tree [tree [r]. lc]. h = tree [tree [r]. rc]. h + 2) {int t = tree [r]. lc; if (tree [tree [t]. lc]. h = tree [tree [r]. rc]. h + 1) {r = zig (r);} else if (tree [t]. rc]. h = tree [tree [r]. rc]. h + 1) {tree [r]. lc = zag (tree [r]. lc); r = zig (r) ;}} else if (tree [tree [r]. lc]. h + 2 = tree [tree [r]. rc]. h) {int t = tree [r]. rc; if (tree [tree [t]. rc]. h = tree [tree [r]. lc]. h + 1) r = zag (r); else if (tree [t]. lc]. h = tree [tree [r]. lc]. h + 1) {tree [r]. rc = zig (tree [r]. rc); r = zag (r) ;}} tree [r]. h = max (tree [tree [r]. lc]. h, tree [tree [r]. rc]. h) + 1 ;}

 

In the main function, calling dele (r, x) must ensure that x is in the subtree. Therefore, you can use find (r, x) first to call dele (r, x)

int main(){   if(find(r,x))    dele(r,x);}
Average search length (ASL)-criteria for measuring search algorithm efficiency

The expected value of the number of key codes required to search for each data element in a data table.

For a data table with n data elements, the average search length when a data element is successfully searched is:

 

Pi indicates the probability that the I-th data element will be searched, and Ci indicates the number of times the key code is compared to the I-th data element.

 

Time: 2017-03-22

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.