20172314 2018-2019-1 Summary of the seventh week of program design and data structure

Source: Internet
Author: User
Summary of teaching material learning content
  • Binary Search Tree: a binary tree with additional attributes. That is, its left child is smaller than the parent node, and its parent node is smaller than or equal to the right child.
  • The binary search tree is defined as an extension of the Binary Tree definition.
  • Operations on the binary search tree
Use a linked list to implement a binary search tree
  • Each binarytreenode object must maintain a reference pointing to the elements stored in the node, and maintain the reference of each child pointing to the node.
  • The linkedbinarysearchtree class provides two constructor functions: one is responsible for creating an empty linkedbinarysearchtree, and the other is responsible for creating a linkedbinarysearchtree whose root node is a specific element. Both constructors only reference the corresponding constructors in the semi binarytree.
  • AddelementOperation: add the element to the appropriate position in the tree based on the value of the given element.
    • If this element is not comparable, this method will throw the nocomparableelementexception exception.
    • If the fruit tree is empty, this element is called a new node.
    • If the fruit tree is not empty, the left child <parent node, parent node <= rules of the right child to add it to the appropriate location, or the left or right child's child.
    • Add elements to a binary tree
  • RemoveelementOperation: When deleting an element from the binary search tree, you must select another node (replacement method to locate this node) to replace the node to be deleted.
    • If no target element is found in the tree, an elementnotfoundexception exception is thrown.
    • Select three scenarios for replacing a node
      • If the deleted node has no children, the replacement returns NULL.
      • The deleted node has only one child. Replacement returns this child.
      • The deleted node has two children. Replacement returns the Middle-order successor (because equal elements are placed on the right)
    • Delete an element from a binary tree
  • RemovealloccurrencesOperation: delete all existing elements from the binary search tree.
    • If no target element is found in the tree, an elementnotfoundexception exception is thrown.
    • If this element is not comparable, this method throws a classcastexception.
    • This method calls the removeelement method once to ensure that an exception is thrown when no specified element exists in the tree.
    • If the fruit tree contains a target element, the removeelement method is called again.
  • RemoveminOperation: according to the definition of the Binary Search Tree, the rightmost node and leftmost element are saved on the rightmost node.
    • If the root node of a tree does not have a left child, the root node is the smallest, and the right child becomes a new root node.
    • If the left child is a leaf node, set the reference of the parent node to null.
    • If the left child is an internal node, the right child of the left child will replace itself as the left child of its parent node.
Ordered list to implement binary search tree
  • One of the main uses of the tree is to provide efficient implementation for other sets.
  • There is a one-to-one correspondence between the methods of the linkedbinarysearchtree class and the methods of the ordered list.
  • List of Common Operations

  • Special Operations for ordered lists

  • Analysis of binarysearchtreelist implementation
    • Binarysearchtreelist is a balanced binary search tree with additional attributes (the maximum depth of any node is log2n, where N is the number of elements stored in the tree ).
    • Tree implementation will make some operations more efficient and some operations more inefficient.
    • The add and remove operations need to rebalance the tree.
    • Implementation Analysis of ordered list linked list and Binary Search Tree
  • Balanced Binary Search Tree
    • If the binary search tree is unbalanced, the efficiency may be lower than that of the linear structure. For example, if the tree is more like a linked list, the efficiency of the tree is actually lower than that of the linked list, because each node has additional overhead.

    • If there is no balancing assumption, when the root is the smallest element in the tree and the inserted element is the largest element in the tree, the time complexity of the addelement operation is O (n) instead of O (logn ).
    • Our goal is to keep the maximum path length of the tree as (or close to) log2n.

Four Methods of balancing tree
  • The maximum length of the path from the root of the tree cannot exceed log2n, and the minimum length must not be less than log2 (n-1)
  • The equilibrium factor refers to the value of the Left subtree minus the right subtree depth.
  • Right hand
    • Generally, the left child rotates around its parent node to the right. The imbalance is caused by long paths in the left subtree of the left child of the root.
    • First, you can calculate the appearance of the original tree after it becomes the Balance Tree. The maximum path length is 3 and the minimum path length is 1. The tree contains 6 elements, therefore, the maximum path length is log26, that is, 2. Three steps are required to balance the tree
      • The left child of the root is called the New Root.
      • Make the original root element the right child of the New Root
      • Make the right child of the left child of the original root become the new left child of the original root
    • Is based on the three-step right-hand process above
  • Left-hand
    • The right child usually rotates around its parent node to the left. The imbalance is caused by long paths appearing in the right subtree of the right child of the root.
    • Similarly, to balance, three steps are required.
      • Make the right child element of the root become a new root element
      • The original root element is called the left child of the new root element.
      • The left child of the right child of the original tree root becomes the right child of the original tree root
    • Is based on the left-hand process of the above three steps
  • Left-hand
    • For the imbalance caused by long paths in the left subtree of the right tree root, the left child of the right tree root needs to be right-handed around its parent node first, let the right child of the root of the tree go left-handed around the root of the tree.

  • Left-right Rotation
    • For the imbalance caused by long paths in the right subtree of the left child of the root tree, the right child of the root tree needs to be left-handed around its parent node first, let the left child of the root of the tree go around the root of the tree for a right-handed operation.
Implement Binary Search Tree: AVL Tree
  • For any node in the tree, if its | balance factor | (the height of the right subtree minus the height of the Left subtree)> 1, the subtree whose node is the root of the tree needs to be rebalance.
  • There are only two ways for a tree (or any subtree of a tree) to become unbalanced: Insert a node or delete a node. Therefore, when performing these two operations, you must update the balance factor and check the tree balance from the place where the node is inserted or deleted. It is recommended that the AVL Tree contain a reference pointing to the parent node for each node.

  • Right hand of the AVL Tree
    • If the equilibrium factor of a node is-2, the left subtree is too long. If the left subtree is-1, the left subtree of the node is a long path, the left child can be balanced once round the initial node.
  • Left-hand of AVL Tree
    • If the balance factor of a node is + 2, the right subtree is too long. If the balance factor of the right child is + 1, this means that the longer path is in the right subtree of the right child, and the right child can be balanced once left around the initial node.
  • Left-hand right of the AVL Tree
    • It is also determined by the balance factor that the balance factor of a node is + 2, and the balance factor of the right child is-1. The left subtree of the right child is too long, you need to perform a right-left rotation (the right-hand child of the right child of the initial node performs a right-hand rotation around the initial node, and the right child of the initial node performs a left-hand rotation around the initial node)
  • AVL Tree Rotation
    • It is also determined by the balance factor that the balance factor of a node is-2, and the balance factor of the right child is + 1. The left child's right subtree is too long, A round-robin is required (the left child of the initial node has a left-hand rotation around the initial node, and the left child of the initial node has a right-hand rotation around the initial node)
Implement Binary Search Tree: red/black tree
  • The red-black tree is a balanced binary search tree, where each node stores a color (red or black, expressed in a Boolean value, false indicates red ). Node color rules:
    • The root node is black.
    • All the children at the Red node are black.
    • Each path from the root of the tree to the leaf contains the same number of black nodes.
  • To some extent, the balance limit in the red and black trees is not as strict as that in the AVL tree, but their order is still logn.
  • The red/black tree path contains up to half of the red nodes and at least half of the Black nodes.
  • The maximum height of the red/black tree is about 2 * logn, so the order for traversing the longest path is still logn.
  • The inserted node is regarded as red, and the empty node is considered as black.
  • The red and black trees indicate:

  • Insert elements in the red/black tree
    • Set the color of the new element to red, then rebalance the tree, change the color of the element according to the property of the red and black tree, and then set the root node to black.
    • The rebalancing after insertion is an iterative process that goes from the insertion point to the root of the tree. There are two termination conditions for the iteration process.
      • (Current = root): The reason is that the black elements in each path are the same, while the root node is always black.
      • (Current. Parent. Color = black): BecauseEach node pointed to by current is red.(In the beginning, the new element is always set to red, so its parent node cannot be red), if the current node's parent node is black, because the number of black nodes is fixed, in addition, during the balancing, the uplink processing has already balanced the bottom face tree of the current node, so as long as this condition is met, the balance can be achieved.
        During each iteration, the following situations occur:
      • Parent node is left child
        • Uncle right is red
          • The parent node is black.
          • Uncle right is black
          • Grandpa is red
          • Current changes from me to parent node
        • Uncle right is black
          • When I am a right child
            • Current changes from me to parent node
            • Change current to left child
            • (The current is the left child step)
            • The parent node is black.
            • Grandpa is red
            • If the grandfather is not empty, let the parent node bypass the grandfather's right hand
      • The parent node is the right child.
        • Uncle left is red
          • The parent node is black.
          • Uncle left is black
          • Grandpa is red
          • Current changed from my grandfather
        • Uncle left is black
          • When I am a left child
            • Current changes from me to parent node
            • Right-handed around current, current becomes right-child
            • (The current step is for the right child)
            • The parent node is black.
            • Grandpa is red
            • If the grandfather is not empty, let the parent node go left-handed
      • The above two cases are symmetric, and the root node will eventually be changed to black. The most important thing to insert is uncle's color.
  • Delete elements from the red/black tree
    • After an element is deleted, it needs to be re-balanced (I .e. re-colored). It is an iteration process and there are two termination conditions:
      • (Current = root)
      • (Current. Color = red )??????
      • If the brother color is red
        • Set brother to black
        • The parent node is red.
        • Right-handed
        • Old brothers, new brothers are equal to the left child of the parent node

          The following steps should be taken whether the brothers are black or red:
      • Both siblings are black/null
        • Set brother color to red
        • Current changes from me to parent node
      • The two siblings are not all black
        • Black for left child
          • Brother's right child is black
          • Red brother
          • Let the right child of the brother round the right hand
          • Left child whose brother is equal to the parent node
      • Neither of the two siblings is black.
        • Color of a sibling Node
        • The parent node is black.
        • Black color for left siblings
        • Right-handed
        • Current changes from me to the root of the tree
      • After the cycle ends, delete the node and set the parent's child reference to null. The color of brothers is the most important thing to delete.
Problems and Solutions in teaching material Learning
  • Problem 1: In the deletion of the red/black tree, an iteration termination condition is (current. Color = red), which cannot be understood.
  • Problem 1: because the number of black nodes in each path is the same, when the current node is red, the iteration conditions are met until the current node is red, and all the rules of the red and black trees are met.
  • Question 2: The removeelement operation code has a problem.
  • Problem 2:

    Public t removeelement (T targetelement) {T result = NULL; If (isempty () {// throw new elementnotfoundexception ("linkedbinarysearchtree ");} else {// The tree is not empty. binarytreenode <t> parent = NULL; If (comparable <t>) targetelement ). equals (root. getelement () {// The element to be deleted is the root node result = root. element; binarytreenode <t> temp = replacement (Root); If (temp = NULL) {// cannot find the node to replace root = NULL ;} else {// Replace with the node found Root node root. element = temp. element; root. setleft (temp. getleft (); root. setright (temp. getright ();} modcount --;} else {// The Child parent = root of the root node to be deleted; If (comparable <t>) targetelement ). compareto (root. getelement () <0) {// result = removeelement (targetelement, Root. getleft (), parent);} else {// result = removeelement (targetelement, Root. getright (), parent) ;}} return result;} private T removeelement (T targetelement, binarytreenode <t> node, binarytreenode <t> parent) {// Delete the target element other than the root node T result = NULL; If (node = NULL) {Throw new elementnotfoundexception ("linkedbinarysearchtree");} else {If (comparable <t>) targetelement ). equals (node. getelement () {// find the target element result = node. element; binarytreenode <t> temp = replacement (node); // Delete the node element // continue searching for the target element to see if the left and right children are if (parent. right = = Node) {parent. right = temp;} else {parent. left = temp;} modcount --;} else {// if the target element is smaller than the root node, use this method again to search for the target element parent = node from the left subtree; If (comparable <t>) targetelement ). compareto (root. getelement () <0) {result = removeelement (targetelement, Root. getleft (), parent);} else {// The target element is larger than the root node. Use this method to search for the target element result = removeelement (targetelement, Root. getright (), parent) ;}} return result ;}// Delete the element private binarytreenode <t> replacement (binarytreenode <t> node) {binarytreenode <t> result = NULL; If (node. left = NULL) & (node. right = NULL) {// If the left and right subtree are empty, this element does not have any children. If the left and right subtree are empty, delete it directly and result = NULL;} else if (node. left! = NULL) & (node. right = NULL) {if there is only a left child, point the parent node to the left child result = node. left;} else if (node. left = NULL) & (node. right! = NULL) {// if there is only a right child, point the parent node to the right child result = node. right;} else {/* First, find the leftmost child of the right subtree (or rightmost child of the Left subtree), that is, the first node of the left (right) subtree in sequence, swap the node with the node to be deleted, and then delete the node (if there is a right subtree, then the right subtree ). In short, we should first find its replacement, then replace the node to be deleted, and then delete the node. */Binarytreenode <t> current = node. right; // initialize the first node on the right, binarytreenode <t> parent = node; // obtain the leftmost node of the right subtree while (current. left! = NULL) {parent = current; current = current. Left;} current. Left = node. Left; // If the node to be queried is if (node. Right! = Current) {parent. Left = current. Right; // you can move the entire tree structure to current. Right = node. Right;} result = current;} return result ;}
  • Question 3: In the removeelement method, the statement "if two children exist at the deleted node, replacement returns the Middle-order Successor" cannot understand which node is returned.
  • Problem 3: In the classroom, the teacher mentioned the precursor node, which is to sort a tree in the middle order to form a sequence, the returned sequencer mentioned in the book means that the pre-node or post-drive node of the deleted node of the sorted sequence can be defined by itself. For example

    The tree is sorted in the middle order of 2, 3, 4, 5, and 6. After Node 3 is deleted, you can return the precursor Node 2 or the rear drive node 4.

20172314 2018-2019-1 Summary of the seventh week of program design and data structure

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.