This is an implementation to test literate programming using noweb and go.

A tree representation

I'll represent a tree using an struct and pointers. A node will be represented by
<node representation>= (U->)
type Node Struct {
        Key     int
        Value   int
        Left    *Node
        Right   *Node
        Parent  *Node
}

A tree will be represented as a set of Nodes which are connected through pointers.

Insert node in a tree

The implementation of the insert procedure will be recursive. There are three cases when inserting a node:

<insert>= (U->)
func (tree *Node) Insert(key, value int) *Node {
        <insert if tree is empty>
        <insert if root has a bigger key>
        <insert if root has a lower key or equal>
}

If the tree is empty, just create a new node and place it as a root:

<insert if tree is empty>= (<-U)
if tree == nil {
        return &Node {
                Key: key,
                Value: value,
        }
}

In the case the new key is lower than the one on the root, look for a place at the left of the root (i.e. tree.Left). If the root has no left child, then that's the place to put it.

<insert if root has a bigger key>= (<-U)
if key < tree.Key {
        if tree.Left == nil {
                tree.Left = &Node {
                        key: key,
                        Value: value,
                        Parent: tree,
                }
        }
        return tree.Left
else {
        return Tree.Left.Insert(key, value)
}

The remaining case is the same as the previous code but using the right child of the root.

<insert if root has a lower key or equal>= (<-U)
if key < tree.Key {
        if tree.Right == nil {
                tree.Right = &Node {
                        key: key,
                        Value: value,
                        Parent: tree,
                }       
        }
        return tree.Right
else {
        return Tree.Right.Insert(key, value)
}

Comment: the case in which the key is equal to the root's key, a new Node is created even though that's not the most efficient whay to do it, but I think the code is cleaner this way.

The entire code

<*>=
package binTree

<node representation>
<insert>