Provides a Binary tree implementation. This node allows only two child nodes (left and right child). It also provides direct access to the left or right child, including assignment to the same.
This inherits from the Tree::TreeNode class.
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 added will be the second node.
If only one child is present, then this will be the left child.
An exception is raised if two children are already present.
# File lib/tree/binarytree.rb, line 61 def add(child) raise "Already has two child nodes" if @children.size == 2 super(child) end
Returns true
if the receiver node is the left child of its
parent. Always returns false
if it is a root node.
# File lib/tree/binarytree.rb, line 92 def isLeftChild? return false if isRoot? self == parent.leftChild end
Returns true
if the receiver node is the right child of its
parent. Always returns false
if it is a root node.
# File lib/tree/binarytree.rb, line 98 def isRightChild? return false if isRoot? self == parent.rightChild end
Returns the left child of the receiver node. Note that left Child == first Child.
# File lib/tree/binarytree.rb, line 68 def leftChild children.first end
Sets the left child of the receiver node. If a previous child existed, it is replaced.
# File lib/tree/binarytree.rb, line 80 def leftChild=(child) @children[0] = child @childrenHash[child.name] = child if child # Assign the name mapping end
Returns the right child of the receiver 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 75 def rightChild children[1] end
Sets the right child of the receiver node. If a previous child existed, it is replaced.
# File lib/tree/binarytree.rb, line 86 def rightChild=(child) @children[1] = child @childrenHash[child.name] = child if child # Assign the name mapping end
Swaps the left and right child nodes of the receiver node with each other.
# File lib/tree/binarytree.rb, line 104 def swap_children tempChild = leftChild self.leftChild = rightChild self.rightChild = tempChild end