`
jimmee
  • 浏览: 529697 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

最简单的平衡树(红-黑树)的实现

阅读更多

在二叉搜索树(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;
	}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics