The process of inserting a node into a binary tree
Insertion on internal nodes is slightly more complex than on leaf nodes. Say that the internal node is node A
and that node B is the child of A. (If the insertion is to insert a right child, then B is the right child of A, and
similarly with a left child insertion.) A assigns its child to the new node and the new node assigns its parent to
A. Then the new node assigns its child to B and B assigns its parent as the new node.
Deletion is the process whereby a node is removed from the tree. Only certain nodes in a binary tree can be
Node with zero or one children
The process of deleting an internal node in a binary tree
Suppose that the node to delete is node A. If A has no children, deletion is accomplished by setting the child
of A's parent to null. If A has one child, set the parent of A's child to A's parent and set the child of A's parent
to A's child.
Node with two children
In a binary tree, a node with two children cannot be deleted unambiguously. However, in certain binary
trees (including binary search trees) these nodes can be deleted, though with a rearrangement of the tree
Pre-order, in-order, and post-order traversal visit each node in a tree by recursively visiting each node in the
left and right subtrees of the root.
In depth-first order, we always attempt to visit the node farthest from the root node that we can, but with the
caveat that it must be a child of a node we have already visited. Unlike a depth-first search on graphs, there is
no need to remember all the nodes we have visited, because a tree cannot contain cycles. Pre-order is a
special case of this. See depth-first search for more information.
Contrasting with depth-first order is breadth-first order, which always attempts to visit the node closest to the
root that it has not already visited.
Methods for storing binary trees
Binary trees can be constructed from programming language primitives in several ways.
Nodes and references
In a language with records and references, binary trees are typically constructed by having a tree node
structure which contains some data and references to its left child and its right child. Sometimes it also
contains a reference to its unique parent. If a node has fewer than two children, some of the child pointers
may be set to a special null value, or to a special sentinel node.
This method of storing binary trees wastes a fair bit of memory, as the pointers will be null (or point to the
sentinel) more than half the time; a more conservative representation alternative is threaded binary tree.
In languages with tagged unions such as ML, a tree node is often a tagged union of two types of nodes, one
of which is a 3-tuple of data, left child, and right child, and the other of which is a "leaf" node, which contains