1 5. Abstract Data Structures & Algorithms 5.1 Data Structure Fundamentals.

Post on 17-Jan-2016

214 views 2 download

Transcript of 1 5. Abstract Data Structures & Algorithms 5.1 Data Structure Fundamentals.

1

5. Abstract Data Structures & Algorithms

5.1 Data Structure Fundamentals

5.1.4 Binary Trees

3

Definition

•Like linked lists, binary trees are dynamic structures.

•Linked lists must be traversed sequentially to find an individual node, which can be inefficient for large lists.

•Binary trees allow binary searching.

4

Definition

•Both lists and trees are for items that have a natural order, not just the order of arrival as with stacks and queues.

•In a binary tree, each node has a possibility of two others coming off it, left or right depending on whether they are less than or greater than it in the chosen order.

5

Definition

•For example, the integers 4, 7, 3, 1, 6 arrive in that order.

•As each one arrives, the rule is “point left if it is less, right if it is more”...

6

Definition

4

73

1 6

7

Definition

•Every tree has a root node (in this case 4).

•If a node is a parent node , it can have 1 or 2 child nodes, no more.

•A node with no children (at the end of a branch) is a terminal or leaf node.

8

Uses

•Search indexes for large files.

•Decision trees.

•File systems.

•Evaluating mathematical expressions.

9

Search index

10

Search index

•Searching for an author in a linked list at worst will take as many operations as there are nodes in the list.

•In a binary tree, at worst, it takes only as many operations as the depth of the tree

•However, efficiency depends on how balanced the tree is.

11

Decision tree

12

Decision tree

•One branch for yes, one for no.

•Used in diagnostics, Sat Nav and call centres.

•A parent node is always a question, a leaf node is an answer.

13

File systems

14

File system

•All operating systems store files in folders (directories) and sub-folders (sub-directories).

•In fact this is just a virtual system of indexing files.

15

Evaluating expressions

•e.g. 4 * ( 1 + 2 ) – 3[in postfix notation: 1 2 + 4 * 3 -]

•To convert to postfix, a binary tree is built from bottom up:

1 2

+ 4

* 3

-