Data structure-two fork tree and two fork lookup tree __ Data structure

Source: Internet
Author: User
Tags comparable int size

First, the order of the tree -two-fork tree-two fork to find the tree is explained more clearly.

One, the tree

A tree is a finite set of n (n≥0) nodes. In any of a non-empty tree:

(1) Having and having only a specific node called root;

(2) When n>1, the remaining nodes can be divided into m (m>0) disjoint finite set T1,T2,...,TM, in which each set itself is a tree and is called the root subtree (subtree). the degree of node (Degree): The number of subtrees owned by the node is called the degree of the node (Degree). A node with a degree of 0 is called a leaf or a terminal node. A node with a degree of not 0 is called a non terminal node or branch node.
the degree of a tree: the maximum of the degrees of each node in the tree.
Children and parents: The root of a node's subtree is called the child of the node, and correspondingly, the node is called the child's parents (parent).
node Level: starting from the root node, the root is the first layer, the root of the child for the second layer, and so on. The maximum level of nodes in a tree is called the depth (Depth) or height of the tree.

If the tree nodes of each subtree as a left-to-right (that is, not interchangeable), the tree is called an ordered tree, otherwise known as the unordered tree.


two, two-fork tree

Binary trees (Binary tree) are characterized in that each node has a maximum of two Shang trees (that is, in the binary tree does not exist more than 2 nodes), and the subtree has a left-right.

The nature of the binary tree:
(1) There are at most 2i-1 nodes (i≥1) on the first layer of the binary tree.
(2) The two-fork tree with a depth of K has at most 2k-1 nodes (k≥1).
(3), for any one binary tree, if its terminal node is n0, the degree of 2 of the knot is N2, then n0=n2+1.

There is a lot of terminology about trees, here do not do too much text explanation, do not want to paint. Below I have found diagram description, graph reference from http://blog.csdn.net/u012152619/article/details/42059325, it can intuitively understand the tree path, root, parent node, child node, leaf node, subtree, layer concepts such as


Three, two fork lookup tree (left < Middle < right)

We start with a special, widely used two-fork tree: A two-fork lookup tree.

The nature of a binary lookup tree:

(1) If its left subtree is not empty, the value of all nodes on the left subtree is less than the value of its root node;
(2) if its right subtree is not empty, the value of all nodes on the right subtree is greater than the value of its root node;
(3), its left and right subtree are also two-fork lookup trees respectively.
In a nutshell, a binary lookup tree is characterized by a node with a key value that is less than this node, and the key value of the right child node is greater than or equal to the parent node.

The basic operation of the binary lookup tree is to find, insert, delete, traverse , which is described below:

1, find (search)

We already know that the binary search tree is characterized by the Zoozi node being less than the parent node and the right child node being greater than or equal to the parent node. When looking for a node, start with the root node, if the element value is less than the root node, turn to the left child node, or to the right child node, and so on until the node is found, or the last leaf node is still not found, then the tree does not have the node


The code is:

  /** lookup Element, returns True */Public
  Boolean search (E e) {
    treenode<e> current = root;//starting from the root element while

    (current!= NULL) {if
      (E.compareto (Current.element) < 0) {//If it is smaller than the current element value, point to the left subtree current
        = current.left;
      else if (E.compareto (current.element) > 0) {//If larger than the current element value, point to the right subtree current
        = Current.right
      of the present element) else//element equals current.element
        return true;//Discovery element, returning True
    } returns

    false;
  }

2, inserting (insert)

Insert a new node first to determine the location of the insertion, the key idea is to determine the location of the new node's parent node.


Code:

/** Insert Element, successfully returns True
  /public boolean insert (E e) {
    if (root = = null)
      root = Createnewnode (e); C3/>else {
      //mark the current parent node position
      treenode<e> parent = null;
      treenode<e> current = root;
      While (the current!= null)
        if (E.compareto (current.element) < 0) {
          parent = current;
          current = Current.left;
        }
        else if (E.compareto (current.element) > 0) {
          parent = current;
          current = Current.right;
        }
        else return
          false;//have duplicate nodes, cannot be inserted

      ///Create a new node to hang under the parent node
       if (E.compareto (parent.element) < 0)
        Parent.left = Createnewnode (e);
       else
        parent.right = Createnewnode (e);
    }

    size++;
    return true; Insert succeeded
  }


3, delete (delete)
Deleting one of the nodes in BST is the most troublesome operation, summarizing the following two ways:

Case 1: There is no left child at the point of deletion, it is only necessary to connect the parent of the node with the child of the current node



CASE2: Delete Point has left child. In this case, we first find the right node of the left subtree of the current node, because the leftmost node of one node is smaller than the leftmost node of the right subtree, the right node is copied to the delete point, and the right node is deleted.





Code:

 /** deletes the node, deletes successfully returns TRUE, does not return false*/public boolean delete (e e) {//mark the deleted node and the node's parent node position in the tree treenode<e> parent = 
    Null
    treenode<e> current = root;
        While (the current!= null) {if (E.compareto (current.element) < 0) {parent = current;
      current = Current.left;
        else if (E.compareto (current.element) > 0) {parent = current;
      current = Current.right; else break; element in this tree} if (current = = null) return false;
      element is not in the tree if (current.left = = null) {//The first case: the element has no left subtree, hangs the right subtree of the current node directly on the right subtree of its parent node//hangs the right subtree of the current node directly on the right subtree of its parent node
      if (parent = null) {root = Current.right;
        else {if (E.compareto (parent.element) < 0) Parent.left = current.right;
      else parent.right = current.right; } else {//The second case: the element has a Zoozi tree, first find the leftmost node of the current node's left subtree//mark the parent and the right node of the current node's left subtree treenode<e> parentofrig Htmost = Current;
      
      treenode<e> rightmost = Current.left;
        To the right, find the leftmost node, because the leftmost node of a node's left subtree is also smaller than the leftmost node of the right subtree (rightmost.right!= null) {parentofrightmost = rightmost; rightmost = Rightmost.right; Always to the right}/* * The purpose of the above code is to find the Zuozi of the deletion node, because the leftmost node of a node is also smaller than the leftmost node of the right subtree.

      placing current.element = rightmost.element; Eliminates the right node if (parentofrightmost.right = = rightmost) Parentofrightmost.right = rightmost.left;//The left child of the right node hung in its parent     
    On the right subtree of the node else//specific situation: Parentofrightmost = = Current Parentofrightmost.left = Rightmost.left;
    } size--; return true;
 Delete succeeded}

Here is a description of the structure of the binary tree:


Tree.java

Package com.hust.cn;
Public interface Tree<e extends comparable<e>> {
  //Lookup element public 
  Boolean search (e e);
  Insert Element Public
  Boolean insert (e e);
  Deletes the element public
  Boolean Delete (e e);

  
  The middle sequence traverses the public
  void Inorder ();
  Subsequent traversal of the public
  void Postorder ();
  Pre-order traversal public
  void preorder ();

  
  Returns the size public
  int getsize ();
  null and void Public
  Boolean isempty ();
  Returns the iterator public
  Java.util.Iterator iterator () for the tree;

Abstracttree.java

Package com.hust.cn;
Public abstract class Abstracttree<e extends Comparable<e>>
    implements tree<e> {
	//in-order traversal Public
  void Inorder () {
  }

  //sequential traversal of the public
  void Postorder () {}//

  forward traversal public
  void Preorder ( {
  }

  ///NULL public
  Boolean IsEmpty () {return
    getsize () = 0;
  }

  Returns the iterator public
  Java.util.Iterator iterator () of the tree () {return
    null;
  }
}
Binarytree.java

Package com.hust.cn; public class Binarytree<e extends comparable<e>> extends abstracttree<e> {protected treenode<e

  > root;//node class, is the inner class protected int size = 0; /** constructor/Public BinaryTree () {}/** object array create a binary lookup tree/Public BinaryTree (e[] objects) {for (int i = 0; I & Lt Objects.length;
  i++) Insert (objects[i]);  /** lookup Element, returns True */public boolean search (e e) {treenode<e> current = root;//starting from root element while
      != null) {if (E.compareto (current.element) < 0) {//If it is smaller than the current element value, point to the left subtree current = Current.left;
      else if (E.compareto (current.element) > 0) {//If larger than the current element value, point to the right subtree current = Current.right of the present element; else//Element equals current.element return true;
  The element is found, returns true} return false; /** Insert Element, successfully returns TRUE/public boolean insert (E e) {if (Root = null) root = Createnewnode (e); A node else {//mark the current parent node position TreEnode<e> parent = null;
      treenode<e> current = root;
          While (the current!= null) if (E.compareto (current.element) < 0) {parent = current;
        current = Current.left;
          else if (E.compareto (current.element) > 0) {parent = current;
        current = Current.right; else return false; There are duplicate nodes that cannot be inserted///Create a new node to hang under the parent node if (E.compareto (parent.element) < 0) Parent.left = Createnewnode (
       e);
    else Parent.right = Createnewnode (e);
    } size++; return true;
  Insert succeeded}/* Create a new node/* protected treenode<e> Createnewnode (e) {return new treenode<e> (e);
  /** in sequence traversal/public void inorder () {inorder (root);
    /** the sequence traversal from the root node, recursive method * * protected void inorder (treenode<e> root) {if (root = null) return;
    Inorder (Root.left);
    System.out.print (Root.element + "");
  Inorder (Root.right);
 /** subsequent traversal * * public void Postorder () {postorder (root);
    /** the subsequent traversal from the root node, recursive method * * protected void Postorder (treenode<e> root) {if (root = null) return;
    Postorder (Root.left);
    Postorder (Root.right);
  System.out.print (Root.element + "");
  /** Pre-order traversal/public void preorder () {preorder (root);
    /** traversal from the root node, recursive method */protected void preorder (treenode<e> root) {if (root = null) return;
    System.out.print (Root.element + "");
    Preorder (Root.left);
  Preorder (root.right);
  /** returns the size of the tree * * public int getsize () {return size;
  /** return root node */public TreeNode getroot () {returns root; /** returns the path from the root node to a specific element/public java.util.arraylist<treenode<e>> path (e e) {java.util.arraylist< treenode<e>> list = new java.util.arraylist<treenode<e>> ()//////array to hold elements on the path treenode<e> current = root; Start while (current!= null) {List.add) from the root node;///Add present element to array IF (E.compareto (Current.element) < 0) {current = Current.left;
      else if (E.compareto (current.element) > 0) {current = Current.right;
    else break; } return list; Returns the node array}/** deletes the node, deletes successfully returns TRUE, does not return false*/public boolean delete (e e) {//mark the deleted node and the node's parent node position in the tree TREENODE&L T 
    E> parent = null;
    treenode<e> current = root;
        While (the current!= null) {if (E.compareto (current.element) < 0) {parent = current;
      current = Current.left;
        else if (E.compareto (current.element) > 0) {parent = current;
      current = Current.right; else break; element in this tree} if (current = = null) return false;
      element is not in the tree if (current.left = = null) {//The first case: the element has no left subtree, hangs the right subtree of the current node directly on the right subtree of its parent node//hangs the right subtree of the current node directly on the right subtree of its parent node
      if (parent = null) {root = Current.right; } else {if (E.compareto (Parent.elemENT) < 0) Parent.left = current.right;
      else parent.right = current.right; } else {//The second case: the element has a Zoozi tree, first find the leftmost node of the current node's left subtree//mark the parent and the right node of the current node's left subtree treenode<e> parentofrig
      Htmost = current;
      
      treenode<e> rightmost = Current.left;
        To the right, find the leftmost node, because the leftmost node of a node's left subtree is also smaller than the leftmost node of the right subtree (rightmost.right!= null) {parentofrightmost = rightmost; rightmost = Rightmost.right; Always to the right}/* * The purpose of the above code is to find the Zuozi of the deletion node, because the leftmost node of a node is also smaller than the leftmost node of the right subtree.

      placing current.element = rightmost.element; Eliminates the right node if (parentofrightmost.right = = rightmost) Parentofrightmost.right = rightmost.left;//The left child of the right node hung in its parent     
    On the right subtree of the node else//specific situation: Parentofrightmost = = Current Parentofrightmost.left = Rightmost.left;
    } size--; return true; Delete succeeded}/** get the middle order iterator/public Java.util.Iterator iterator () {REturn Inorderiterator ();
  /** Create an Iterator class */public Java.util.Iterator Inorderiterator () {return new inorderiterator (); }//In-order iterator class, inner class Inorderiterator implements Java.util.Iterator {//Storage element Array private java.util.arraylist& Lt
    e> list = new java.util.arraylist<e> (); private int current = 0; The position of the current element in the array public inorderiterator () {inorder ();//in Sequence traversal binary tree}/** from the root sequence traversal/private void inorder
    () {inorder (root);
      /** in the Order traversal subtree */private void inorder (treenode<e> root) {if (root = null) return;
      Inorder (Root.left);
      List.add (root.element);
    Inorder (Root.right);

      /** Traverse next element/public boolean hasnext () {if (Current < List.size ()) return true;
    return false;
    /** gets the current element and points the pointer to another element */public Object Next () {return list.get (current++); /** move out of the current element/public void Remove () {delete (list.get);Current element list.clear (); Clean array inorder ();
    Re-order traversal of the array}}/** clear all elements of the tree * * (public void. * () {root = null;
  size = 0;
    /** internal class, tree node class * * public static class Treenode<e extends Comparable<e>> {E element;
    Treenode<e> left;

    Treenode<e> right;
    Public TreeNode (e e) {element = E;
 }
  }

}
Testbinarytree.java

Package com.hust.cn; public class Testbinarytree {public static void main (string[] args) {//Create a binary lookup tree binarytree<string> tre
    E = new binarytree<string> ();
    Tree.insert ("George");
    Tree.insert ("Michael");
    Tree.insert ("Tom");
    Tree.insert ("Adam");
    Tree.insert ("Jones");
    Tree.insert ("Peter");

    Tree.insert ("Daniel");
    Traversal tree System.out.println ("inorder (sorted):");
    Tree.inorder ();
    System.out.println ("\npostorder:");
    Tree.postorder ();
    System.out.println ("\npreorder:");
    Tree.preorder ();

    System.out.println ("\nthe number of nodes is" + tree.getsize ());

    Find an element System.out.println ("\nis Peter in") + Tree.search ("Peter");
    A path from Root through Peter System.out.println ("\na path from the ROOT to Peter is:");
    java.util.arraylist<binarytree.treenode<string>> Path = Tree.path ("Peter"); for (int i = 0; path!= null && i < path.size (); i++) SysteM.out.print (Path.get (i). Element + "");
    Using arrays to construct a binary lookup tree, and in-sequence traversal integer[] numbers = {2, 4, 3, 1, 8, 5, 6, 7};
    binarytree<integer> inttree = new binarytree<integer> (numbers);
    System.out.println ("\ninorder (sorted):");
  Inttree.inorder ();
 }
}

Test results:




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.