红黑树插入

CSDN 上另外一篇帖子上的程序是错的,所以在这里给出一个正确的程序.

 

/**
* Introduction to Algorithms, Second Edition
* true3 Red-Black Trees
*
* 红黑树的条件:
* 1,每个节点标记为“红”或“黑”。
* 2.根标记为“黑”。
* 3.所有叶节点(nil)标记为“黑”。
* 4.如果一个节点为“红”,则它的两个节点都为“黑”。
* 5.对每个的节点,从该节点至后继叶节点包含相同数量的“黑”节点。
@author religiose
*
*/

package  redblacktree;

import  java.util.ArrayList;
import  java.util.List;

public   class  RedBlackTree  {
    
/**
     * 数据节点
     
*/

    
public static class Node {
        
int key;
        Node parent; 
//父节点
        Node left; //左子节点
        Node right; //右子节点
        boolean color; //节点颜色
        public Node(int key,boolean color) {
            
this.key = key;
            
this.color = color;
        }


        
public String toString() {
            
return String.valueOf(key);
        }

    }


    
/**
     * 颜色
     
*/

//  private enum Color { RED, BLACK};

    Node root; 
//根节点

    Node nil; 
//空节点


    
/**
     * 构造函数
     
*/

    
public RedBlackTree() {
        Node nil 
= new Node(-1,false);
        root 
= nil;
    }


    
/**
     * 左旋转。
     * 
@param x 支点
     
*/

    
private void leftRotate(Node x) {
        Node y 
= x.right; // y是x的右子节点
        x.right = y.left; // y的左子树转换成x的右子树
        if (y.left != nil)
            y.left.parent 
= x;
        y.parent 
= x.parent; // 用y替换x的位置
        if (x.parent == nil) {
            root 
= y;
        }
 else if (x == x.parent.left) {
            x.parent.left 
= y;
        }
 else {
            x.parent.right 
= y;
        }


        y.left 
= x; // 将x设置为y的左子节点
        x.parent = y;
    }


    
/**
     * 右旋转。
     * 
@param x 支点
     
*/

    
private void rightRotate(Node y) {
        Node x 
= y.left; // y是x的右子节点
        y.left = x.right; // y的左子树转换成x的右子树
        if (x.right != nil)
            x.right.parent 
= y;
        x.parent 
= y.parent; // 用y替换x的位置
        if (y.parent == nil) {
            root 
= x;
        }
 else if (y == y.parent.left) {
            y.parent.left 
= x;
        }
 else {
            y.parent.right 
= x;
        }


        x.right 
= y; // 将x设置为y的左子节点
        y.parent = x;
    }


    
/**
     * 采用递归法查找键值为k的节点。
     * 
@param k 节点的键值
     * 
@return 返回键值为k的节点
     
*/

    
public Node search(int k) {
        
return search(root, k);
    }


    
/**
     * 采用递归法查找键值为k的节点。
     * 
@param x 当前节点
     * 
@param k 节点的键值
     * 
@return 返回键值为k的节点
     
*/

    
private Node search(Node x, int k) {
        
if(x == nil || k == x.key) {
            
return x;
        }
 else if(k < x.key) {
            
return search(x.left, k);
        }
 else {
            
return search(x.right, k);
        }

    }


    
/**
     * 采用迭代法查找键值为k的节点。
     * 
@param x 当前节点
     * 
@param k 节点的键值
     * 
@return 返回键值为k的节点
     
*/

    
public Node iterativeSearch(int k) {
        
return iterativeSearch(root, k);
    }


    
/**
     * 采用迭代法查找键值为k的节点。
     * 
@param x 当前节点
     * 
@param k 节点的键值
     * 
@return 返回键值为k的节点
     
*/

    
private Node iterativeSearch(Node x, int k) {
        
while(x != nil && k != x.key) {
            
if(k < x.key) {
                x 
= x.left;
            }
 else {
                x 
= x.right;
            }

        }

        
return x;
    }


    
/**
     * 返回树的最小键值的节点。
     * 
@return 最小键值的节点
     
*/

    
public Node minimum() {
        
return minimum(root);
    }

    
/**
     * 返回树的最小键值的节点。
     * 
@param x 当前节点
     * 
@return 最小键值的节点
     
*/

    
private Node minimum(Node x) {
        
while(x.left != nil) {
            x 
= x.left;
        }

        
return x;
    }

    
/**
     * 返回树的最大键值的节点。
     * 
@return 最大键值的节点
     
*/

    
public Node maximum() {
        
return maximum(root);
    }


    
/**
     * 返回树的最大键值的节点。
     * 
@param x 当前节点
     * 
@return 最大键值的节点
     
*/

    
private Node maximum(Node x) {
        
while(x.right != nil) {
            x 
= x.right;
        }

        
return x;
    }


    
/**
     * 返回指定节点x的后继节点。
     * 
@param x 当前节点
     * 
@return x的后继节点;如果x具有最大键值,返回null
     
*/

    
public Node successor(Node x) {
        
if(x.right != nil) {
            
return minimum(x.right);
        }

        Node y 
= x.parent;
        
while(y != nil && x == y.right) {
            x 
= y;
            y 
= y.parent;
        }

        
return y;
    }


    
/**
     * 返回指定节点x的前驱节点。
     * 
@param x 当前节点
     * 
@return x的前驱节点;如果x具有最小键值,返回null
     
*/

    
public Node predecessor(Node x) {
        
if(x.left != nil) {
            
return maximum(x.left);
        }

        Node y 
= x.parent;
        
while(y != nil && x == y.left) {
            x 
= y;
            y 
= y.parent;
        }

        
return y;
    }


    
/**
     * 插入节点。
     * 
@param z 待插入节点
     
*/

    
public void insert(Node z) {
        Node y 
= nil; //当前节点的父节点
        Node x = root; //当前节点
        while(x != nil) //迭代查寻z应该所在的位置
            y = x;
            
if(z.key < x.key) {
                x 
= x.left;
            }
 else {
                x 
= x.right;
            }

        }

        z.parent 
= y;
        
if(y == nil) {
            root 
= z; //如果没有父节点,则插入的节点是根节点。
        }
 else if(z.key < y.key) {
            y.left 
= z;
        }
 else {
            y.right 
= z;
        }

        z.left 
= nil;
        z.right 
= nil;
        z.color 
= true;
        insertFixup(z);
    }

    
/**
     * 按红黑树规则进行调整。
     * 
@param z 待插入节点
     
*/

    
public void insertFixup(Node z) {
          
while (z.parent != null && z.parent.parent != null && z.parent.color == true ) //违反条件4,并且保证z有爷爷
            if (z.parent == z.parent.parent.left) //z的父节点是左子节点
              Node y = z.parent.parent.right;
              
if (y == null || y.color == false//如果z的叔叔是黑或空
                if (z == z.parent.right) //如果z是右子节点,左旋
                  z = z.parent;
                  leftRotate(z);
                }

                z.parent.color 
= false//z的父亲为黑(叔叔为黑)
                z.parent.parent.color = true//z的爷爷为红
                rightRotate(z.parent.parent); // 右旋
              }

              
else  //如果z的叔叔是红
                z.parent.color = false//将z的父亲和叔叔设为黑
                y.color = false;
                z.parent.parent.color 
= true//z的爷爷设为红
                z = z.parent.parent; //迭代
              }

            }
 else //z的父节点是右子节点,反向对称
              Node y = z.parent.parent.left;
              
if (y == null || y.color == false)  {
                
if (z == z.parent.left) {
                  z 
= z.parent;
                  rightRotate(z);
                }

                z.parent.color 
= false;
                z.parent.parent.color 
= true;
                leftRotate(z.parent.parent);
              }

             
else {
                z.parent.color 
= false;
                y.color 
= false;
                z.parent.parent.color 
= true;
                z 
= z.parent.parent;
              }

            }

          }

      root.color 
= false//满足条件2
    }


    
/**
     * 删除节点。
     * 
@param z 待删除节点
     
*/

    
public Node delete(Node z) {
        Node y 
= null;
        Node x 
= null;
        
if (z.left == nil || z.right == nil) {
            y 
= z;
        }
 else {
            y 
= successor(z);
        }


        
if (y.left != nil) {
            x 
= y.left;
        }
 else {
            x 
= y.right;
        }


        x.parent 
= y.parent;

        
if (y.parent == nil) {
            root 
= x;
        }
 else if (y == y.parent.left) {
            y.parent.left 
= x;
        }
 else {
            y.parent.right 
= x;
        }


        
if (y != z) //如果z包含两个子节点,用y替换z的位置
            z.key = y.key;

        }


        
if(y.color == false{
            deleteFixup(x);
        }

        
return y;
    }

    
/**
     * 按红黑树规则进行调整。
     * 
@param z 待删除节点
     
*/

    
private void deleteFixup(Node x) {
        
while(x != root && x.color == false{
            
if(x == x.parent.left) {
                Node w 
= x.parent.right;
                
if(w.color == true{
                    w.color 
= false;
                    x.parent.color 
= true;
                    leftRotate(x.parent);
                    w 
= x.parent.right;
                }

                
if(w.left.color == false && w.right.color == false{
                    w.color 
= true;
                    x 
= x.parent;

                }
 else {
                    
if(w.right.color == false{
                        w.left.color 
= false;
                        w.color 
= true;
                        rightRotate(w);
                        w 
= x.parent.right;
                    }


                    w.color 
= x.parent.color;
                    x.parent.color 
= false;
                    w.right.color 
= false;
                    leftRotate(x.parent);
                    x 
= root;
                }

            }
 else {
                Node w 
= x.parent.left;
                
if(w.color == true{
                    w.color 
= false;
                    x.parent.color 
= true;
                    rightRotate(x.parent);
                    w 
= x.parent.left;
                }

                
if(w.right.color == false && w.left.color == false{
                    w.color 
= true;
                    x 
= x.parent;
                }
 else {
                    
if(w.left.color == false{
                        w.right.color 
= false;
                        w.color 
= true;
                        leftRotate(w);
                        w 
= x.parent.left;
                        
//preorderWalk();
                    }

                    w.color 
= x.parent.color;
                    x.parent.color 
= false;
                    w.left.color 
= false;
                    rightRotate(x.parent);
                    x 
= root;
                }

            }

        }

        x.color 
= false;
    }


    
/**
     * 中序遍历。即从小到大排序。
     * 
@return 返回已排序的节点列表
     
*/

    
public List inorderWalk() {
        List list 
= new ArrayList();
        inorderWalk(root, list);
        
return list;
    }


    
/**
     * 中序遍历。
     * 
@param x 当前节点
     * 
@param list 遍历结果存储在list中
     
*/

    
private void inorderWalk(Node x, List list) {
        
if(x != nil) {
            inorderWalk(x.left, list);
            list.add(x);
            inorderWalk(x.right, list);
        }

    }


    
/**
     * 前序遍历打印。即从小到大排序。
     * 
@return 返回已排序的节点列表
     
*/

    
public List preorderWalk() {
        List list 
= new ArrayList();
        preorderWalk(root,list);
        
return list;
    }


    
/**
     * 中序遍历打印。
     * 
@param x 当前节点
     * 
@param list 遍历结果存储在list中
     
*/

    
private void preorderWalk(Node x,List list) {
        
if(x != nil) {
          list.add(x);
            preorderWalk(x.left,list);
            preorderWalk(x.right,list);

        }

    }

}


测试程序:
package redblacktree;
import java.util.List;
//import junit.framework.TestCase;
public class RedBlackTreeTest extends RedBlackTree {
    static RedBlackTree tree = new RedBlackTree();
    public static void testLinkedList() {
      // 插入N个随机节点
      Node Left = new Node(25,true);
      Node Right = new Node(75,true);
      int count = 50;
      tree.root.key = 50;
      tree.root.color = false;
      tree.root.left = Left;
      tree.root.right = Right;
      Left.parent = tree.root;
      Right.parent = tree.root;
      for (int i = 0; i < count; ) {
        int key = (int) (Math.random() * 100);
        if (tree.search(key) == tree.nil) {
          tree.insert(new RedBlackTree.Node(key,true));
          i++;
        }
      }
    }
        //测试最大值,最小值
//        List list = tree.inorderWalk();
//        verifyOrdered(list);
//        assertEquals(count, list.size());
//        assertEquals(list.get(0), tree.minimum());
//        assertEquals(list.get(list.size() - 1), tree.maximum());
        //测试后继
//        RedBlackTree.Node min = tree.minimum(), succ = null;
//        while((succ=tree.successor(min)) != tree.nil) {
//            assertTrue(succ.key > min.key);
//            min = succ;
//        }
        //测试前驱
//        RedBlackTree.Node max = tree.maximum(), pre = null;
//        while((pre=tree.predecessor(max)) != tree.nil) {
//            assertTrue(succ.key < max.key);
//            max = pre;
//        }
        //测试删除
//        int[] keys = new int[list.size()];
//        for(int i = 0; i < keys.length; i++) {
//            keys[i] = list.get(i).key;
//        }
//        PermuteBySorting.permute(keys);
//        for (int i = 0; i < count; i++) {
//            RedBlackTree.Node node = tree.search(keys[i]);
//            assertNotNull(node);
//            tree.delete(node);
//            assertEquals(tree.nil, tree.search(keys[i]));
//            verifyOrdered(tree.inorderWalk());
//        }
//    }
    private static boolean verifyOrdered(List list) {
        for (int i = 1; i < list.size(); i++) {
            if (((Node)(list.get(i - 1))).key > ((Node)(list.get(i))).key) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) throws Exception {
      RedBlackTreeTest A = new RedBlackTreeTest();
      A.testLinkedList();
      List list1 = tree.inorderWalk();
      int i = 0;
      System.out.println(list1.size());
      while (i < list1.size()) {
        System.out.print(((Node)(list1.get(i))).key + "   ");
        i++;
      }
      System.out.println(A.verifyOrdered(list1));
      List list2 = tree.preorderWalk();
      i = 0;
      while(i < list2.size()){
        System.out.print(((Node)(list2.get(i))).key + "   ");
        i++;
      }
      System.out.println(" ");
      i = 0;
      while(i < list2.size()){
       System.out.print(((Node)(list2.get(i))).color + " ");
       i++;
     }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值