Mercurial > public > think_complexity
comparison redblacktree.py @ 15:b163f18eaf92
Starting a redblacktree.py module for Section 3.4, Exercise 4.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Tue, 18 Dec 2012 19:54:04 -0600 |
parents | |
children | a00e97bcdb4a |
comparison
equal
deleted
inserted
replaced
14:bc2c07a059be | 15:b163f18eaf92 |
---|---|
1 """A red-black tree for Section 3.4, Exercise 4 in Allen Downey's _Think | |
2 Complexity_ book. | |
3 | |
4 http://greenteapress.com/complexity | |
5 | |
6 Copyright (C) 2012 Brian G. Neal. | |
7 | |
8 Permission is hereby granted, free of charge, to any person obtaining a copy of | |
9 this software and associated documentation files (the "Software"), to deal in | |
10 the Software without restriction, including without limitation the rights to | |
11 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | |
12 the Software, and to permit persons to whom the Software is furnished to do so, | |
13 subject to the following conditions: | |
14 | |
15 The above copyright notice and this permission notice shall be included in all | |
16 copies or substantial portions of the Software. | |
17 | |
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | |
20 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | |
21 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | |
22 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | |
23 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
24 | |
25 """ | |
26 | |
27 BLACK, RED = range(1) | |
28 | |
29 class Node(object): | |
30 """A node class for red-black trees. | |
31 | |
32 A node has an optional parent, and optional left and right children. Each | |
33 node also has a color, either red or black. A node has a key and an optional | |
34 value. The key is used to order the red black tree by calling the "<" | |
35 operator when comparing keys. | |
36 | |
37 In a red-black tree, nil children are always considered black. | |
38 | |
39 """ | |
40 | |
41 def __init__(self, key, color=RED, value=None): | |
42 self.key = key | |
43 self.value = value | |
44 self.color = color | |
45 | |
46 self.parent = None | |
47 self.left = None | |
48 self.right = None | |
49 | |
50 @property | |
51 def grandparent(self): | |
52 """Return the grandparent of this node, or None if it does not exist.""" | |
53 return self.parent.parent if self.parent else None | |
54 | |
55 @property | |
56 def uncle(self): | |
57 """Return this node's uncle if it exists, or None if not. | |
58 | |
59 An uncle is a parent's sibling. | |
60 | |
61 """ | |
62 g = self.grandparent | |
63 if g: | |
64 return g.left if g.right is self.parent else g.right | |
65 return None |