10 DSA Trees
10 DSA Trees
Trees
Trees
A rooted tree data structure stores information in nodes
Similar to linked lists:
There is a first node, or root
Each node has variable number of references to successors
Each node, other than the root, has exactly one node pointing to
it
Terminology: Parent Child Relations
All nodes have zero or more child nodes or children
I has three children: J, K and L
For all nodes other than the root node, there is one parent
node
H is the parent of: I
Terminology: Degree
The degree of a node is defined as the number of its children
deg(I)=3
Nodes with the same parent are siblings
J, K, and L are siblings
Terminology: Leaf And Internal Nodes
Nodes with degree zero are also called leaf nodes
All other nodes are said to be internal nodes, that is, they are
internal to the tree
Terminology: Leaf Nodes Examples
Terminology: Internal Nodes Example
Terminology: Path
A path is a sequence of nodes (a 0 , a 1 , . . . , an)
Where ak + 1 is a child of ak
Start of these
paths
End of these
paths
Terminology: Depth (or Level)
For each node in a tree, there exists a unique path from the
root node to that node
14
1
7
Terminology: Height
The height of a tree is defined as the maximum depth of any
node within the tree
1
7
Terminology: Ancestors And Descendants
If a path exists from node a to node b
a is an ancestor of b
b is a descendent of a
B C Height
Root Node
D E F
Leaves
Ancestors of
G
H
H I Descendants of
B
Example: HTML
HTML document has a tree structure
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>This i s a <u>Heading</u></h1>
<html> titl
<head e
> <title>Hello World!</title> headin
</head> g
<body>
<h1>This i s a <u>Heading</u></h1>
body of
page <p>This i s a paragraph wit h some
<u>underlined</u> t e x t . < / p >
</body>
</html>
paragra
underlini ph
ng
Example: HTML
The nested tags define a tree rooted at the HTML tag
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>This i s a <u>Heading</u></h1>