Provides a Binary tree implementation. This tree node allows only two child nodes (left and right childs). It also provides direct access to the left and right children, including assignment to the same.
Adds the specified child node to the receiver node. The child node’s parent is set to be the receiver. The child nodes are added in the order of addition, i.e., the first child added becomes the left node, and the second child will be the second node. If only one child is present, then this will be the left child.
# File lib/tree/binarytree.rb, line 59 def add(child) raise "Already has two child nodes" if @children.size == 2 super(child) end
Returns true if this is the left child of its parent. Always returns false if this is the root node.
# File lib/tree/binarytree.rb, line 92 def isLeftChild? return nil if isRoot? self == parent.leftChild end
Returns true if this is the right child of its parent. Always returns false if this is the root node.
# File lib/tree/binarytree.rb, line 99 def isRightChild? return nil if isRoot? self == parent.rightChild end
Returns the left child node. Note that left Child == first Child
# File lib/tree/binarytree.rb, line 67 def leftChild children.first end
Sets the left child. If a previous child existed, it is replaced.
# File lib/tree/binarytree.rb, line 79 def leftChild=(child) @children[0] = child @childrenHash[child.name] = child if child # Assign the name mapping end
Returns the right child node. Note that right child == last child unless there is only one child. Returns nil if the right child does not exist.
# File lib/tree/binarytree.rb, line 74 def rightChild children[1] end
Sets the right child. If a previous child existed, it is replaced.
# File lib/tree/binarytree.rb, line 85 def rightChild=(child) @children[1] = child @childrenHash[child.name] = child if child # Assign the name mapping end
Swaps the left and right children with each other
# File lib/tree/binarytree.rb, line 105 def swap_children tempChild = leftChild self.leftChild= rightChild self.rightChild= tempChild end