tree.rb
# Deletes a node from the tree. Returns the deleted node
Deletes a node from the tree. Returns the deleted node
Deletes a node from the tree . Returns the deleted node
def delete(value, start_node = nil)
    parent = nil
    node = path(value, start_node) { |path_node| parent = path_node } 
    return if node.nil? 
    replace_with = Proc.new do |node, parent, replacement|
      if parent
        parent < node ? parent.right = replacement : parent.left = replacement
      else
        @root = replacement
      end
    end
    case [node.left, node.right]
    in [nil, nil] | [_, nil] | [nil, _] 
      replace_with.call(node, parent, node.left || node.right)  
    else 
      successor_parent, successor = node, node.right
      loop do
        break if successor.left.nil?
        successor_parent, successor = successor, successor.left
      end
      replace_with.call(successor, successor_parent, successor.left || successor.right)
      successor.left = node.left    
      successor.right = node.right  
      replace_with.call(node, parent, successor)
    end
    return node  return deleted node
  end
def delete ( value , start_node = nil ) parent = nil node = path ( value , start_node ) { | path_node | parent = path_node } return if node . nil? replace_with = Proc . new do | node , parent , replacement | if parent parent < node ? parent . right = replacement : parent . left = replacement else @root = replacement end end case [ node . left , node . right ] in [ nil , nil ] | [ _ , nil ] | [ nil , _ ] replace_with . call ( node , parent , node . left || node . right ) else successor_parent , successor = node , node . right loop do break if successor . left . nil? successor_parent , successor = successor , successor . left end replace_with . call ( successor , successor_parent , successor . left || successor . right ) successor . left = node . left successor . right = node . right replace_with . call ( node , parent , successor ) end return node end
Deletes a node from the tree.
Deletes a node from the tree .
# find target node and it's parent # quit if no node is found # Proc to be called when a node's place is to be taken by another # delete # zero children, only one (L) child, only one (R) child # replace with child # child is nil in zero children case # two children # find next largest node # replace successor with its children, i.e. delete successor from its original place # replace node with successor # copy links # # return deleted node
value
<not_specific>
start_node
<not_specific>