Вы находитесь на странице: 1из 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 1


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.

a A tree
• Different types of trees :
- Rooted tree
- Ordered tree b c
- M-ary tree and binary tree
d e f g h

Programming and Data Structures 2


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 3


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

Programming and Data Structures 4


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. a

• Subtree :
- any node of a tree, with all of its descendants.
b c
• Depth of a node :
- Depth of root node is 0.
- Depth of any other node is 1 greater than d e
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.
it’s 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 7


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 right child
b c
Right subtree
Left subtree d e f g

h
Programming and Data Structures 8
Examples of Trees

• A free tree

• A binary tree

• A rooted binary tree

• A forest

Programming and Data Structures 9


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; data : 0
BTreeNode left = null;
BTreeNode right = null; 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 John

5 16 James Joseph
4 7 13 21
Jack Jesus
2

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

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. a

• Postorder traversal:
- do postorder traversal of left subtree. b c
- do postorder traversal of right subtree.
- visit the node last and process.
- i.e. visits and processes each node in the tree AFTER d e
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
Example of Tree Traversal
12

5 16

4 7 13 21

Preorder:
Inorder:
Postorder:

Programming and Data Structures 20


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

Inorder void postorder(BTreeNode the_node)


Preorder
{
if (the_node == null)
; // do nothing
else
{
postorder(the_node.left);
postorder(the_node.right);
System.out.print(the_node.data);
}
} Postorder
Programming and Data Structures 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 statement

equality expression ; ...

expression == expression LHS = expression

var var + const var var

a b 1 x y
Programming and Data Structures 23
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

+ 1

* /

5 3 - 4

9 1

Programming and Data Structures 25

Вам также может понравиться