You are on page 1of 25

Non-Linear Data Structures

We will have a look at the following; Trees Tree terminology Binary Search Trees Tree Traversal

Programming and Data Structures

A Tree
In terms of data structures, what do we mean by a tree?
Definition: - a set of related interconnected nodes in a hierarchical structure. - a non-empty collection of vertices and edges that satisfies certain requirements. - structure resembles branches of a tree, hence the name. Different types of trees : - Rooted tree - Ordered tree - M-ary tree and binary tree

a b d i e f g c h

A tree

Programming and Data Structures

Trees
Where have you seen a tree structure before? Examples of trees: - Directory tree - Family tree - Company organization chart - Table of contents - etc.

Programming and Data Structures

Tree Terminology (1)


A vertex (or node) is a simple object that can have a name and can carry other associated information The first or top node in a tree is called the root node. An edge is a connection between two vertices A path in a tree is a list of distinct vertices in which successive vertices are connected by edges in the tree. example: {a, b, d, i } is path. The defining property of a tree is that there is precisely one path connecting any two nodes. A disjoint set of trees is called a forest Nodes with no children are leaves or terminal nodes
Programming and Data Structures 4

root edges

a b d i e f g c

Nodes/Vertices

leaves

Tree Terminology (2)


Child of a node u : - Any node reachable from u by 1 edge. Parent node : - If b is a child of a, then a is the parent of b. - All nodes except root have exactly one parent. Subtree : - any node of a tree, with all of its descendants. Depth of a node : - Depth of root node is 0. - Depth of any other node is 1 greater than depth of its parent. Height : - Maximum of all depths.
Programming and Data Structures 5

Rooted Tree
A Rooted Tree is one where we designate one node as the root (i.e. the tree examples we have been looking at so far are all rooted trees). In computer science we normally reserve the term tree to refer to rooted trees. The more general structure is a free tree In a rooted tree, any node is the root of a subtree consisting of it and the nodes below it. There is exactly one path between the root and each of the other nodes in the tree Each node except the root has exactly one node above it in the tree, (i.e. its parent), and we extend the family analogy talking of children, siblings, or grandparents
Programming and Data Structures 6

Ordered Tree
An ordered tree is a rooted tree in which the order of the children at every node is specified. If each node must have a specific number of children appearing in a specific order, then we have an M-ary tree The simplest type of M-ary tree is the binary tree

Programming and Data Structures

Binary Trees
A binary tree is a tree where each node has exactly zero, one or two children. i.e. each parent can have no more than 2 children. As with any Abstract Data Structure we can implement a binary tree in a number of ways, using arrays, strings, or structures and pointers

a
left child

b e f

right child

Right subtree Left subtree

d h

Programming and Data Structures

Examples of Trees
A free tree A binary tree A rooted binary tree

A forest

Programming and Data Structures

Representing A Binary Tree Data Structure in Java


How do we represent a binary tree using Java? One way of representing A node of a binary tree in Java as follows: class BTreeNode { int data = 0; BTreeNode left = null; BTreeNode right = null; }

data : 0 left right

null

null

We may then build our binary tree using this node structure.
Programming and Data Structures 10

Constructing the Binary Tree


Lets draw the following code sequence:
BTreeNode root = null, temp = null; root = new BTreeNode(); root.data = 5; temp = new BTreeNode(); temp.data = 2; temp.left = null; temp.right = null; root.left = temp; root.right = null;

Programming and Data Structures

11

Binary Search Trees


A binary tree which conforms to the following properties is called a binary search tree. Properties: - Each value (key) in the tree exists at most once (i.e. no duplicates). - The "greater-than" and "less-than" relations are well defined for the data value. - Sorting constraints:- for every node n : All data in the left subtree of n is less than the data in the root of that subtree. All data in the right subtree of n is greater than the data in the root of that subtree.

Programming and Data Structures

12

Examples

12 5 4 2
BST for numbers

John

16 7 13 21
Jack

James Jesus

Joseph

BST for names

Programming and Data Structures

13

Example Draw a BST (1)


Add 8, 10, 5, 1, 7, 11 to an empty BST, in that order:

Programming and Data Structures

14

Example Draw a BST (2)


What if we change the order in which the numbers are added? Add 1, 5, 7, 8, 10, 11 to a BST in that order:

Programming and Data Structures

15

How to Construct a BST in Java


The most intuitive way of creating a BST/adding nodes to a BST is to

use recursive approach. What are the base and recursive cases? : Base case: if tree is empty, create new node for item Recursive case: if key < root's value, add to the left subtree, otherwise to the right subtree

Programming and Data Structures

16

BST Add Node Method


Code for add node method :
BTreeNode Add_node(BTreeNode node, int value) { if(node == null) { node = new BTreeNode(); node.data = value; node.left = null; node.right = null; return node; } else { if ((value > node.data) && (node.right == null)) return node.right = Add_node(node.right, value); else if ((value > node.data) && (node.right != null)) return Add_node(node.right, value); else if ((value < node.data) && (node.left == null)) return node.left = Add_node(node.left, value); else return Add_node(node.left, value); } } // Method returns newly added node // The base case // Create the new node // Give it specified data // Set up left and right pointers // Return the new node to the calling method // The Recursive cases // If node is a leaf and node to add is right child // Prepare to accept a new right child // Else if node not a leaf, traverse as appropriate // If node is a leaf and node to add is left child // Prepare to accept a new left child // Else node not a leaf, traverse as appropriate

Programming and Data Structures

17

Tree Traversal
As with lists, we would like to be able to traverse through all nodes in our tree. Problem: what order should the nodes be visited in? - Top-down? - Left-to-right? - Bottom-up? We may traverse a binary tree in 3 ways : - preorder - postorder - inorder
Programming and Data Structures 18

Types of Traversal
Preorder traversal: - visit the node first and process. - do preorder traversal of left subtree. - do preorder traversal of right subtree. - i.e. visits and processes each node in a tree BEFORE visiting and processing its children. Postorder traversal: - do postorder traversal of left subtree. - do postorder traversal of right subtree. - visit the node last and process. - i.e. visits and processes each node in the tree AFTER visiting and processing its children. Inorder traversal: - do inorder traversal of left subtree. - visit the node and process. - do inorder traversal of right subtree. - i.e. processes nodes in the tree in an ascending sorted order.
Programming and Data Structures 19

a c

Example of Tree Traversal


12 5 4 2 Preorder: Inorder: Postorder: 7 13 16 21

Programming and Data Structures

20

Traversal Methods
void inorder(BTreeNode the_node) { if (the_node == null) ; // do nothing else { inorder(the_node.left); System.out.print(the_node.data); inorder(the_node.right); } } void preorder(BTreeNode the_node) { if (the_node == null) ; // do nothing else { System.out.print(the_node.data); preorder(the_node.left); preorder(the_node.right); } }

Inorder

void postorder(BTreeNode the_node) { if (the_node == null) ; // do nothing else { postorder(the_node.left); postorder(the_node.right); System.out.print(the_node.data); } } Programming and Data Structures

Preorder

Postorder
21

Tree Examples : Expression Trees


Compiling programs is a complex task: All Statements have a fixed form (syntax) Statements can be ordered and nested almost arbitrarily The compiler generates syntax trees that represent programs. The process of building a syntax tree is called parsing. After the syntax tree is built, the tree is traversed and for each node code is generated.

Programming and Data Structures

22

Tree Examples : A Syntax Tree


Consider the C++ statement: if (a == b + 1) x = y; else ...
statement
if

expression

statement else expression ;

statement ...

equality expression var a == expression var b +

LHS =

expression var y
23

const var 1 x

Programming and Data Structures

Tree Examples : Binary Expression Trees


A binary expression tree is a syntax tree used to represent the meaning of a mathematical expression. Nodes are normal arithmetical operators such as + - / * Leaves are operands Structure of the tree defines result Expression can be evaluated easily from their binary expression tree.

Programming and Data Structures

24

Binary Expression Trees : Example


5 * 3 + ( 9 - 1) / 4 - 1
+ * 5 3 9 1 / 4

Programming and Data Structures

25

You might also like