欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最简单的平衡树(红-黑树)的实现 博客分类: 算法J2SE 算法二叉平衡树2-3树红黑树 

程序员文章站 2024-03-17 19:16:34
...

在二叉搜索树(BST)的基础上,要实现一颗平衡树,可以使用2-3树的方式,2-3树的直接实现,相对比较复杂

,因此算法的研究者们提出了红-黑树的实现方式。

 

package com.test;

public class RedBlackTree<Key extends Comparable<Key>, Value> {
	private static final boolean RED = true;
	private static final boolean BLACK = false;
	
	private Node root;

	private class Node {
		private Key key;
		private Value value;
		private boolean color;
		
		private Node left, right;

		public Node(Key key, Value value, boolean color) {
			super();
			this.key = key;
			this.value = value;
			this.color = color;
		}
	}
	
	private boolean isRed(Node x) {
		if (x == null) return false;
		
		return x.color == RED;
	}
	
	private Node rotateLeft(Node h) {
		Node x = h.right;
		h.right = x.left;
		x.left = h;
		x.color = h.color;
		h.color = RED;
		
		return x;
	}
	
	private Node rotateRight(Node h) {
		Node x = h.left;
		h.left = x.right;
		x.right = h;
		x.color = h.color;
		h.color = RED;
		
		return x;
	}
	
	private void flipColors(Node h) {
		h.color = RED;
		h.left.color = BLACK;
		h.right.color = BLACK;
	} 
	
	public void put(Key key, Value val) {
		root = put(root, key, val);
	}
	
	private Node put(Node h, Key key, Value val) {
		if (h == null) {
			return new Node(key, val, RED);
		}
		
		int cmp = key.compareTo(h.key);
		if (cmp < 0) {
			h.left = put(h.left, key, val);
		} else if (cmp > 0) {
			h.right = put(h.right, key, val);
		} else {
			h.value = val;
		}
		
		if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
		if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
		if (isRed(h.left) && isRed(h.right)) flipColors(h);
		
		return h;
	}
	
	public Value get(Key key) {
		Node x = root;
		while (x != null) {
			int cmp = key.compareTo(x.key);
			if (cmp < 0) {
				x = x.left;
			} else if (cmp > 0) {
				x = x.right;
			} else {
				return x.value;
			}
		}
		
		return null;
	}
}