Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SS-003] Removing element from RBTree #4

Merged
merged 10 commits into from
Oct 12, 2024

Conversation

J0onYEong
Copy link
Owner

New features

  • removing element from RBTree
  • restructure logic editted

restructure logic editted

When restructuring occurred, the original children of the node becoming the new parent were being discarded. I have added logic to properly reassign the original children into the restructured tree.

a method that appends node to certaion node is implemented

func append(_ value: Element) throws {
    
    guard let rootNode else {
        // Root node is empty
        createRoot(value)
        return
    }
    
    // new node is always red
    let newNode: RBTreeNode = .init(value: value, color: .red)
    
    // append new node
    try append(newNode, to: rootNode)
}
private func append(_ node: Node, to: Node) throws {
    
    var currentParentNode: RBTreeNode! = to
    
    while(true) {
        
        if currentParentNode.isEmptyNode {
            // CurrentNode is empty leaf node
            currentParentNode.parent?.setToChild(node)
            break
        }
        
        if currentParentNode > node {
            // go left
            currentParentNode = currentParentNode.leftChild
        } else if currentParentNode < node {
            // go right
            currentParentNode = currentParentNode.rightChild
        } else {
            throw RBTreeError.duplicatedElement
        }
    }
    
    // start checking double red
    resolveDoubleRed(node)
}

below code is added to end of the restructuring method

[originalLeftNode, originalRightNode]
    .compactMap { $0 }
    .forEach { relocatingNode in
        // this insertion not related to duplication
        try! append(relocatingNode, to: middleNode)
    }

@J0onYEong J0onYEong merged commit 8ccf48b into main Oct 12, 2024
@J0onYEong J0onYEong deleted the feature/delete_item_from_RBTree branch October 12, 2024 15:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant