一篇長文讓你完全瞭解紅黑樹

📖前言

面試中老是遇到紅黑樹,這是個常常讓人悲劇的數據結構。紅黑樹的規則複雜,紅黑的概念也讓人費解,是個很難理解的東西,並且在實際編碼中,不少庫都提供了紅黑樹,開發者不多輪子它。其結果是,面試只要遇到紅黑樹,就是凶多吉少的結果——起碼我就是這樣的。node

紅黑樹是個頗有價值的數據結構,這也能夠從上邊的論述中略見一斑:計算機的理念是以簡爲美,代碼一目瞭然、概念邏輯清晰,而引入的紅黑樹概念複雜,只有兩種可能,這種複雜是有極大好處的,或者提出紅黑樹的是個草包:)。答案顯然是前者。此外,不少類庫甚至大名鼎鼎的內核都提供或者使用了紅黑樹,這也說明了其自有牛逼之處。面試

基本概念

首先列一下紅黑樹的概念:數據結構

  1. 節點是兩種顏色之一:紅或者黑1this

    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.編碼