Trees - General & Binary


General trees

A tree is a hierarchical structure of nodes.
Each node contains some information and one or more links to other nodes further down the hierarchy.

A tree consists of nodes where each node is the root node of a subtree.

A leaf node is the root node of an empty tree.


Binary Trees

Binary trees are a special case of general trees.

Each node can have two children at most.

Implementation:
Use dynamic memory allocation to create and destroy nodes when required.

Eg. struct node { DataType data;
                  node     *right;
                  node     *left;
                };

We require a pointer variable to hold the address of the root node.
                 node *root = 0;   // empty tree
All other nodes are accessed by traversing the tree until they are located.

eg. non empty tree.

Tree Traversals

Eg. one of each of the above.

Expression trees


Binary Search Trees

Eg. M,D,P,B,N,Z,O,B,A,C

An inorder traversal will visit each node of the tree by ascending order of the node data.


Tree Traversals


Binary Search Trees


Eg. M,D,P,B,N,Z,O,A,C
                    M
                  /   \
                 D     P
               /      / \
              B      N   Z
            /  \      \
           A    C      O
preorder traversal = M,D,B,A,C,P,N,O,Z
inorder traversal = A,B,C,D,M,N,O,P,Z
postorder traversal = A,C,B,D,O,N,Z,P,M

An inorder traversal will visit each node of the tree by ascending order of the node data.

We require a pointer variable to hold the address of the root node. 
                 node *root = 0;   // empty tree
All other nodes are accessed by traversing the tree until they are located.


About Me         Back      Home        Mail to me
Hosted by www.Geocities.ws

1