Skip to content

Commit

Permalink
Merge pull request kodecocodes#868 from dcherednikov/red-black-tree-e…
Browse files Browse the repository at this point in the history
…nhancement

Add getPredecessor() and getKey() methods to RBTreeNode.
  • Loading branch information
kelvinlauKL authored Mar 21, 2019
2 parents 3da1288 + 7065c1a commit 791cc66
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions Red-Black Tree/README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ From [CLRS]
## Methods

Nodes:
* `nodeX.getPredecessor()` Returns the inorder predecessor of nodeX
* `nodeX.getSuccessor()` Returns the inorder successor of nodeX
* `nodeX.minimum()` Returns the node with the minimum key of the subtree of nodeX
* `nodeX.maximum()` Returns the node with the maximum key of the subtree of nodeX
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ public class RBTreeNode<T: Comparable>: Equatable {
self.init(key: nil, leftChild: nil, rightChild: nil, parent: nil)
self.color = .black
}

public func getKey() -> T? {
return key
}

var isRoot: Bool {
return parent == nil
Expand Down Expand Up @@ -120,9 +124,30 @@ extension RBTreeNode {
}
}

// MARK: - Finding a nodes successor
// MARK: - Finding a nodes successor and predecessor

extension RBTreeNode {
/*
* Returns the inorder predecessor node of a node
* The predecessor is a node with the next smaller key value of the current node
*/
public func getPredecessor() -> RBNode? {
// if node has left child: predecessor is min of this left tree
if let leftChild = leftChild, !leftChild.isNullLeaf {
return leftChild.maximum()
}
// else go upward while node is left child
var currentNode = self
var parent = currentNode.parent
while currentNode.isLeftChild {
if let parent = parent {
currentNode = parent
}
parent = currentNode.parent
}
return parent
}

/*
* Returns the inorder successor node of a node
* The successor is a node with the next larger key value of the current node
Expand Down

0 comments on commit 791cc66

Please sign in to comment.