一篇长文让你彻底了解红黑树

📖前言

面试中总是遇到红黑树,这是个经常让人悲剧的数据结构。红黑树的规则复杂,红黑的概念也让人费解,是个很难理解的东西,而且在实际编码中,很多库都提供了红黑树,开发者很少轮子它。其结果是,面试只要遇到红黑树,就是凶多吉少的结果——起码我就是这样的。

红黑树是个很有价值的数据结构,这也可以从上边的论述中略见一斑:计算机的理念是以简为美,代码一目了然、概念逻辑清晰,而引入的红黑树概念复杂,只有两种可能,这种复杂是有极大好处的,或者提出红黑树的是个草包:)。答案显然是前者。此外,很多类库甚至大名鼎鼎的内核都提供或者使用了红黑树,这也说明了其自有牛逼之处。

基本概念

首先列一下红黑树的概念:

  1. 节点是两种颜色之一:红或者黑1

    A node is either red or black.
    The root is black. (This rule is sometimes omitted. Since the root can always be changed from red to black, but not necessarily vice-versa, this rule has little effect on analysis.)
    All leaves (NIL) are black. (All leaves are same color as the root.)
    Every red node must have two black child nodes.
    Every path from a given node to any of its descendant leaves contains the same number of black nodes.

posted @ 2014-08-16 07:48  斯啦丝拉  阅读(413)  评论(0编辑  收藏  举报