Balanced binary trees (Balance binary tree)--avl tree

Source: Internet
Author: User

The search efficiency of the two-fork lookup tree described in the previous section depends on the shape of the two-fork sort tree, while the structure of a homogeneous two-fork lookup tree is related to the order in which the nodes are inserted, and the order of insertion is often unpredictable.

(1) If the maximum or minimum value is inserted first, the entire binary search tree will have no left subtree or right subtree.

(2) In the worst case, the order of insertion is already orderly, at this time the binary search tree will become a diagonal tree, at this time become a linear edge, the efficiency of the search suddenly decreased, the time complexity of the Edge is O (n)

(3) So the efficiency of binary search tree is between O (Logn) and O (n).

Based on the above situation, this requires us to find a dynamic balance method, for any insertion sequence can construct a homogeneous, balanced two-fork search tree, which we described below the balanced binary tree .

Balanced binary Tree properties:

(1) The depth of the Saozi right subtree of the root node differs by up to 1. (2) The Saozi right sub-leaf of the root node is a balanced binary tree.

balance factor: the balance factor of each node is the difference between the Zuozi of the node and the depth of the right subtree.

The idea of constructing a balanced binary tree : In the process of constructing a two-fork search tree, whenever a node is inserted, the first check is whether the tree is broken after insertion, and if the tree is resized, it becomes a balanced binary tree after insertion.


Here are 4 things you can do to adjust the tree when the balanced binary tree is inserted:

(1) LL type

B L, BR, respectively, represents the left and right sub-tree of Node B, AR is Node A, and the depth is H. Inserting node X into the left subtree of B causes 1 of the balance factor of Node A to become 2,a out of balance.

The newly inserted node is the left subtree of the left child inserted in Node A, which belongs to the ll type. According to the principle of the shoulder pole, the support node from a to B, and clockwise rotation, after rotation, a and BR conflict, the use of rotation priority principle, the A node as the B node of the right child, b node of the right child off to become a node of the left child.

(2) RR type

B L , bR represents the left and right sub-tree of Node B, AR is Node A, and the depth is H. The node x is inserted into the right subtree of B, causing the balance factor of Node A to be 1 to become -2,a out of balance.

The newly inserted node is in the right child tree of the right child in Node A, which belongs to the ll type. According to the principle of the pole, the support node right A to B, and counterclockwise rotation, after rotation, a and BL conflict, the use of rotation priority principle, the A node as the b node of the left child, b node of the left child off to become a node of the right child.

(3) LR type

Node x is inserted in the left child's right subtree of the root node, causing the balance factor of Node A to be 1 to the 2,a node, which belongs to the LR type, which needs to be rotated 2 times.

First Rotation: The root node does not move, first adjust the node A of the left sub-tree. The support node is adjusted from B to C, counterclockwise, at this time B and C left sub-tree conflict, rotation priority, B as the left child of C, C's left child fell down to become B's right child, at this time C became a left child.

                               

Second Rotation: Adjusts the imbalance factor. Adjust the support node from a to C and rotate clockwise accordingly. At this point, a and C right child conflict, will a as C's right child, C's right child falls off to become a left child.

(4) RL type

Similar to the LR type, it also requires two adjustments. Node x is inserted in the right child's left subtree of the root node, so that the balance factor of Node A-1 becomes the -2,a node loses balance, here is the RL type, need to rotate 2 times .

First Rotation: The root node does not move, first adjust the node A of the right sub-tree. Adjust the support node from B to C, clockwise,

at this point B and C right subtree conflict, rotation priority, will b as C's right child, C's right child.

Second rotation: Adjusts the imbalance factor. Adjust the support node from a to C and rotate counterclockwise accordingly.

At this point, a and C left child conflict, will a as C's left child, C's left child fell off to become a right child.

Through the above analysis, we have understood the construction of a balanced binary tree and the basic process and ideas, which is the essence of the balanced binary tree, regardless of the insertion sequence is how, we can be adjusted to build a balanced binary tree, to ensure that the binary tree of each node of the balance factor will not be greater than 1, to ensure that the depth of the tree to , so the number of comparisons will be less, time complexity will be reduced, and the time complexity of finding in the balanced binary tree is O (logn). Better than binary search tree performance.




A simple implementation of a balanced binary tree:

Package Org.tt.

Balancetree; /** * Balanced binary tree Simple implementation   */public class avltree<t extends Comparable<?
	Super t>> {private avlnode<t> root;//AVL Root/** * Initialized to Empty tree * * Public avltree () {root = null;
	/** * Insert Data in AVL tree */public void Insert (T x) {root = insert (x, root);
		/** * Find the smallest data in the AVL tree */public T findmin () {if (IsEmpty ()) System.out.println ("Tree Empty");
	return Findmin (root). element;
		/** * Find the largest data in the AVL tree */public T Findmax () {if (IsEmpty ()) System.out.println ("Tree Empty");
	return Findmax (root). element;
	}/** * Search, find record, find return True otherwise return false */public Boolean find (T x) {return find (x, root);
	}/** * Empty AVL tree */public void Clear () {root = null;
	}/** * Determines if NULL */public boolean isEmpty () {return root = = NULL;
		}/** * Sort the output AVL tree, using the middle order output */public void Printtree () {if (IsEmpty ()) System.out.println ("Empty tree");
	else Printtree (root); /** * Start with the root node and insert the new node in the appropriate location */private AVLnode<t> Insert (T x, avlnode<t> root) {if (root = null) return new avlnode<t> (x, NULL, NULL);

		int compareresult = X.compareto (root.element); if (Compareresult < 0) {Root.left = insert (x, root.left);//insert X into record if (height (root.left)-Height (root.right)
				= = 2)//Break Balance if (X.compareto (root.left.element) < 0)//ll type (left-left type) root = Rotatewithleftchild (root);	else root = doublewithleftchild (root); LR type (left and right)} else if (Compareresult > 0) {root.right = insert (x, root.right);//Insert X into if (height (root.righ T)-height (root.left) = = 2)//Break Balance if (X.compareto (root.right.element) > 0)//RR (right-right type) root = Rotatewithright
				Child (Root);
		else//RL root = Doublewithrightchild (root); } else;
	Duplicate data, do nothing root.height = Math.max (height (root.left), height (root.right)) + 1;//update height return root;
		}/** * Find minimum value */private avlnode<t> findmin (avlnode<t> N) {if (n = = null) return n; WHile (N.left! = null) n = n.left;
	return n;
		}/** * Find maximum value */private avlnode<t> Findmax (avlnode<t> N) {if (n = = null) return n;
		while (n.right! = null) n = n.right;
	return n;
		}/** * Search (Find), start with a node as the root lookup */@SuppressWarnings ("Unchecked") Private Boolean find (T x, avlnode<?> root) {

			while (root = null) {int compareresult = X.compareto ((T) root.element);
			if (Compareresult < 0) root = root.left;
			else if (Compareresult > 0) root = root.right; else return true; Find} return false;
			Not found}/** * in sequence traversal AVL tree */private void Printtree (avlnode<t> n) {if (n! = null) {Printtree (n.left);
			System.out.print (N.element + "");
		Printtree (N.right);
	}}/** * Find the height of the AVL tree */private int height (avlnode<t> n) {return n = = null? -1:n.height; }/** * with left subtree rotation for LL type */private avlnode<t> Rotatewithleftchild (avlnode<t> N) {avlnode<t> k =
		N.left; N.leFT = k.right;
		K.right = n;
		N.height = Math.max (height (n.left), height (n.right)) + 1;
		K.height = Math.max (height (k.left), n.height) + 1;
	return k;  }/** * with right subtree rotation for RR type */private avlnode<t> Rotatewithrightchild (avlnode<t> N) {avlnode<t> k =
		N.right;
		N.right = K.left;
		K.left = n;
		N.height = Math.max (height (n.left), height (n.right)) + 1;
		K.height = Math.max (height (k.right), n.height) + 1;
	return k; }/** * Dual rotation for LR type */private avlnode<t> Doublewithleftchild (avlnode<t> n) {n.left = Rotatewithright
		Child (N.left);
	return Rotatewithleftchild (n); }/** * Dual rotation for RL type */private avlnode<t> Doublewithrightchild (avlnode<t> n) {n.right = Rotatewithlef
		Tchild (N.right);
	return Rotatewithrightchild (n);

		} public static void Main (string[] args) {avltree<integer> t = new avltree<integer> ();
		Int[] Value = {6, 1, 20, 7, 10, 8, 9, 3, 14, 5, 18};
		for (int v:value) {T.insert (v);
		}System.out.println ("Middle sequence Traversal:");
		
		T.printtree ();
		System.out.println ();
		
		System.out.println ("Height of the tree:" + t.height (t.root));
		SYSTEM.OUT.PRINTLN ("Minimum value:" + t.findmin ());
		SYSTEM.OUT.PRINTLN ("Maximum value:" + T.findmax ());
	System.out.println ("Find": "+ t.find (10)"); }

}

Results:


AVL Node class:

Package Org.tt. Balancetree;

public class Avlnode<t> {

	T element;//Data in node
	avlnode<t> left;//child avlnode<t> right
	;// Right child
	int height;//Node height

	avlnode (T theelement) {This
		(theelement, NULL, NULL);
	}

	Avlnode (T theelement, Avlnode<t> LT, avlnode<t> rt) {
		element = theelement;
		left = lt;
		right = RT;
		Height = 0;
	}

}


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.