You are on page 1of 13

CS221A – Data Structures &

Algorithms
Trees
Trees
• An ADT that can store data hierarchically. With
a parent child relationship.
• Widely-used data structure that emulates a
hierarchical tree structure with a set of linked
nodes.
• It is a connected graph where each node has a
set of zero or more children nodes, and at
most one parent node.
Trees
• Node is a structure which may contain a value, a
condition, or represent a separate data structure
(which could be a tree of its own).
– Each node in a tree has zero or more child nodes,
which are below it in the tree (by convention, trees
grow down, not up as they do in nature).
– A node that has a child is called the child's parent
node (or ancestor node, or superior).
– A node has at most one parent.
– Nodes that do not have any children are called leaf
nodes. They are also referred to as terminal nodes.
Trees
• A simple unordered
tree;
– the node labeled 7
has two children,
labeled 2 and 6, one
parent, labeled 2.
The root node, at
the top, has no
parent.
Trees
• The topmost node in a
tree is called the root Links or edges Root Node
node.
– The root node will not
have parents.
– It is the node at which
operations on the tree
commonly begin
(although some
algorithms begin with the
leaf nodes and work up
ending at the root).
– All other nodes can be
reached from it by
following links or edges.
Trees
• The height of a node
Height of the
is the length of the Tree : 3
longest downward
path to a leaf from 2
2

that node.
1 1
• The height of the 0

root is the height of 0 0


0
the tree.
Trees
• The depth of a node is the
length of the path to its
root (i.e., its root path).
• An internal node or inner
node is any node of a tree 0
that has child nodes and is
thus not a leaf node. 1 1
• Stepping through the items
of a tree, by means of the
connections between 2 2 2
parents and children, is
called walking the tree or 3 3
Tree Traversal. 3

Inner Node
Trees
• Tree is a collection of
N nodes, one of
which is the root and
N - 1 edges.
–N=9
–E=8
Trees Implementation
Tree Implementation
Tree Implementation
• Each Node Maintains Data and a pointer to
each of its child nodes.
• As Number of Children per Node is an
unknown , we keep the children of each node
in a linked list of tree nodes.
Tree Implementation
• typedef struct TreeNode *PtrToNode;
• struct TreeNode
• {
– ElementType Element;
– PtrToNode FirstChild;
– PtrToNode NextSibling;
• }
Tree Implementation
• void Traverse(Tree t)
• {
– printf (tElement);
– if (tFirstChild != Null)
• Traverse(tFirstChild);
– if (tNextSibling !=Null)
• Traverse(tNextSibling);
• }

You might also like