Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
lint files
  • Loading branch information
weihanglo committed Feb 4, 2017
commit 78da2c7b4719f55faaa69f2ae0c0324eb3423db0
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class BinarySearchTree<T: Comparable> {
public convenience init(array: [T]) {
precondition(array.count > 0)
self.init(value: array.first!)
for v in array.dropFirst() {
for v in array.dropFirst() {
insert(value: v)
}
}
Expand Down Expand Up @@ -106,32 +106,32 @@ extension BinarySearchTree {
*/
@discardableResult public func remove() -> BinarySearchTree? {
let replacement: BinarySearchTree?

// Replacement for current node can be either biggest one on the left or
// smallest one on the right, whichever is not nil
if let right = right {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the significance of handling the right child before the left?

Copy link
Contributor Author

@weihanglo weihanglo Feb 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous version before 942e3b1 use successor to replace the node with 2 children. The unit tests are also based on this logic. I am kind of lazy to modify all the test cases 😵.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright cool. I think this checks out. Merging!

replacement = right.minimum()
} else if let left = left {
replacement = left.maximum()
} else {
replacement = nil;
replacement = nil
}
replacement?.remove();

replacement?.remove()

// Place the replacement on current node's position
replacement?.right = right;
replacement?.left = left;
replacement?.right = right
replacement?.left = left
right?.parent = replacement
left?.parent = replacement
reconnectParentTo(node:replacement);
reconnectParentTo(node:replacement)

// The current node is no longer part of the tree, so clean it up.
parent = nil
left = nil
right = nil
return replacement;

return replacement
}

private func reconnectParentTo(node: BinarySearchTree?) {
Expand Down Expand Up @@ -324,7 +324,7 @@ extension BinarySearchTree: CustomStringConvertible {
}
return s
}

public func toArray() -> [T] {
return map { $0 }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,3 @@ print(tree)
tree.search(x: 10)
tree.search(x: 1)
tree.search(x: 11)