Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Data Structure

2022-2023
BAYAN O. MOHAMMED
Introduction to Tree

2
2
Overview
 Tree data structure
 Binary tree
 Binary search trees
* To design and implement a binary search tree .
* To insert an element to a binary search tree .

3
3
Introduction to Tree
➢ Tree is a non-linear data structure.
➢ Data in a tree is stored in hierarchy.
Example of tree application:
• Represent algebraic formulas
• Store data in hierarchy form. Ex: algebraic formulas : (1+2)*3

organization chart
• Artificial intelligence – information is
accessed based on certain decision which is
stored in a tree.

organization chart

4
Definitions

 A tree T is a set of nodes that form a directed a cyclic graph (DAG)


such that:
 Each non-empty tree has a root node and zero or more sub-trees T1, …, Tk
 Each sub-tree is a tree Recursive definition
 An internal node is connected to its children by a directed edge

 Each node in a tree has only one parent


 Except the root, which has no parent

5
5
Tree Terminology
➢Any two vertices must have one and only one
path between them else its not a tree.

➢Trees are hierarchical


• Parent-child relationship between two nodes
• Ancestor-descendant relationships among
nodes

6
Tree Terminology

Tree Not tree

7
Tree Terminology

8
8
Tree Terminology

9
Tree Terminology

10
Tree Terminology

11
Tree Terminology

•The height of ni is the length of the longest path from ni to a leaf.


•All leaves are at height 0.

• E is at depth 1 and height 2; F is at depth 1 and height 1; the height of the


tree is 3. The depth of a tree is equal to the depth of the deepest leaf; this
is always equal to the height of the tree.

12
Tree Terminology

13
Example

14
Example

3
15
Definitions: node relationships

B,C,D,E,F,G are siblings


K,L,M are siblings
B,C,H,I,P,Q,K,L,M,N are leaves

The path from A to Q is A – E – J – Q (with length 3)


A,E,J are proper ancestors of Q
E,J,Q, I,P are proper descendants of A

16
16
Example

Height of each node? e.g., height(E)=2, height(L)=0


Height of tree?
= 3 (height of longest path from root)
Depth of each node?
Depth of tree? e.g., depth(E)=1, depth(L)=2
= 3 (length of the path to the deepest node) 17
Algorithm for computing the depth

18
Algorithm for computing the Height

19
Thank you for your attendance

You might also like