Skip to content

Commit 791cc66

Browse files
authored
Merge pull request kodecocodes#868 from dcherednikov/red-black-tree-enhancement
Add getPredecessor() and getKey() methods to RBTreeNode.
2 parents 3da1288 + 7065c1a commit 791cc66

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Diff for: Red-Black Tree/README.markdown

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ From [CLRS]
2929
## Methods
3030

3131
Nodes:
32+
* `nodeX.getPredecessor()` Returns the inorder predecessor of nodeX
3233
* `nodeX.getSuccessor()` Returns the inorder successor of nodeX
3334
* `nodeX.minimum()` Returns the node with the minimum key of the subtree of nodeX
3435
* `nodeX.maximum()` Returns the node with the maximum key of the subtree of nodeX

Diff for: Red-Black Tree/RedBlackTree.playground/Sources/RedBlackTree.swift

+26-1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@ public class RBTreeNode<T: Comparable>: Equatable {
6060
self.init(key: nil, leftChild: nil, rightChild: nil, parent: nil)
6161
self.color = .black
6262
}
63+
64+
public func getKey() -> T? {
65+
return key
66+
}
6367

6468
var isRoot: Bool {
6569
return parent == nil
@@ -120,9 +124,30 @@ extension RBTreeNode {
120124
}
121125
}
122126

123-
// MARK: - Finding a nodes successor
127+
// MARK: - Finding a nodes successor and predecessor
124128

125129
extension RBTreeNode {
130+
/*
131+
* Returns the inorder predecessor node of a node
132+
* The predecessor is a node with the next smaller key value of the current node
133+
*/
134+
public func getPredecessor() -> RBNode? {
135+
// if node has left child: predecessor is min of this left tree
136+
if let leftChild = leftChild, !leftChild.isNullLeaf {
137+
return leftChild.maximum()
138+
}
139+
// else go upward while node is left child
140+
var currentNode = self
141+
var parent = currentNode.parent
142+
while currentNode.isLeftChild {
143+
if let parent = parent {
144+
currentNode = parent
145+
}
146+
parent = currentNode.parent
147+
}
148+
return parent
149+
}
150+
126151
/*
127152
* Returns the inorder successor node of a node
128153
* The successor is a node with the next larger key value of the current node

0 commit comments

Comments
 (0)