Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Understanding Trees: Structure, Terminology, Classifications, Traversals, Study notes of Data Structures and Algorithms

An in-depth exploration of trees as a non-linear hierarchical data structure. Topics covered include tree terminology, classifications (binary, balanced, complete, full), traversals (preorder, postorder, level-order), and various implementation techniques (array-based, linked nodes). The document also includes a brief introduction to decision trees and their applications.

Typology: Study notes

Pre 2010

Uploaded on 08/17/2009

koofers-user-k1x
koofers-user-k1x 🇺🇸

10 documents

1 / 8

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
4/13/09
1
16.1 – Trees
! A tree is a non-linear hierarchical
structure
! Tree is comprised of a set of nodes
in which elements are stored and
edges connect one node to another
! A node can have only one parent,
but may have multiple children
! Nodes that have the same parent are
siblings
! There is only one root node in the
tree
! The root is the only node which has
no parent
16.1 – Tree Terminology
! The level of a node is the length of
the path from the root to the node
! The path length is determined by
counting the number of edges that
must be followed to get from the root
to the node
! The height (or depth) of a tree is the
length of the longest path from the
root to a leaf
A
B C
E
D
F G
Level
0
1
3
2
! A node that has no children is a
leaf node
! A note that is not the root and
has at least one child is an
internal node
! A subtree is a tree structure that
makes up part of another tree
! We can follow a path through a
tree from parent to child, starting
at the root
! A node is an ancestor of
another node if it is above it on
the path from the root.
! Nodes that can be reached by
following a path from a particular
node are the descendants of
that node
16.1 – Tree Classifications
! Trees in which nodes may have
at most two children are called
binary trees
! A tree is considered to be
balanced if all of the leaves of the
tree are on the same level or at
least within one level of each
other
! Trees can be classified in
many ways
! One important criterion is the
maximum number of children
any node in the tree may
have
! This is sometimes referred to
as the order of the tree
! General trees have no limit to
the number of children a
node may have
! A tree that limits each node to
no more than n children is
referred to as an n-ary tree
16.1 – Balanced, Complete and Full
! A balanced n-ary tree with m elements will have a height of lognm
! A balanced binary tree with n nodes has a height of log2n
! An n-ary tree is full if all leaves of the tree are at the same height
and every non-leaf node has exactly n children
! A tree is complete if it is full, or full to the next-to-last level with all
leaves at the bottom level on the left side of the tree
pf3
pf4
pf5
pf8

Partial preview of the text

Download Understanding Trees: Structure, Terminology, Classifications, Traversals and more Study notes Data Structures and Algorithms in PDF only on Docsity!

16.1 – Trees

A tree is a non-linear hierarchical

structure

Tree is comprised of a set of nodes

in which elements are stored and

edges connect one node to another

A node can have only one parent ,

but may have multiple children

Nodes that have the same parent are

siblings

There is only one root node in the

tree

The root is the only node which has

no parent

16.1 – Tree Terminology

The level of a node is the length of

the path from the root to the node

The path length is determined by

counting the number of edges that

must be followed to get from the root

to the node

The height (or depth ) of a tree is the

length of the longest path from the

root to a leaf

A

B C

D E

F G

Level

A node that has no children is a

leaf node

A note that is not the root and

has at least one child is an

internal node

A subtree is a tree structure that

makes up part of another tree

We can follow a path through a

tree from parent to child, starting

at the root

A node is an ancestor of

another node if it is above it on

the path from the root.

Nodes that can be reached by

following a path from a particular

node are the descendants of

that node

16.1 – Tree Classifications

Trees in which nodes may have

at most two children are called

binary trees

A tree is considered to be

balanced if all of the leaves of the

tree are on the same level or at

least within one level of each

other

Trees can be classified in

many ways

One important criterion is the

maximum number of children

any node in the tree may

have

This is sometimes referred to

as the order of the tree

General trees have no limit to

the number of children a

node may have

A tree that limits each node to

no more than n children is

referred to as an n-ary tree

16.1 – Balanced, Complete and Full

A balanced n-ary tree with m elements will have a height of lognm

A balanced binary tree with n nodes has a height of log 2 n

An n-ary tree is full if all leaves of the tree are at the same height

and every non-leaf node has exactly n children

A tree is complete if it is full, or full to the next-to-last level with all

leaves at the bottom level on the left side of the tree

16.2 – Tree Traversals

Because of the non-linear nature of a tree, traversing a tree is

generally more interesting than traversing a linear structure

A particular type of traversal simply dictates the order in which

the elements of a collection are assessed

16.2 – Pseudocode of PreInPost Traversals

Visit the root in between

the traversals of the left

and right subtrees

Traverse (left) Visit Node Traverse (right)

Visit the root node after

the traversals of the left

and right subtrees

Traverse (left) Traverse (right) Visit Node

Nodes are visited before

any subtrees are visited

Visit Node Traverse (left) Traverse (right) 16.2 – Level-Order Traversal

Visit the nodes on each level, left to right, top to bottom starting

at the root

Enqueue the root node of the tree While the queue is not empty{ Dequeue node Visit node Enqueue left child of node Enqueue right child of node } 16.3 – Strategies for Implementing Trees Array-based implementations are the less obvious choice, but sometimes useful Computed Links in an Array: 0 1 2 3 4 5 6 7 A B C D E F A B C D E F G

wasted space

16.4 – javafoundations.BinaryTree // Returns a reference to the element in the tree matching // the specified target. public T find (T target); // Returns true if the binary tree contains no elements, and // false otherwise. public boolean isEmpty(); // public Returns the int size(); number of elements in this binary tree. // Returns the string representation of the binary tree. public String toString(); // Returns a preorder traversal on the binary tree. public Iterator preorder(); // Returns an inorder traversal on the binary tree. public Iterator inorder(); // Returns a postorder traversal on the binary tree. public Iterator postorder(); // Performs a level-order traversal on the binary tree. }^ public^ Iterator^ levelorder(); 16.4 – A Binary Tree Implementation

A possible set of operations for a

binary tree is shown in the

BinaryTree interface

BinaryTree has no methods to

add a particular element, or to

remove a particular element from

the tree

Refined versions of binary tree

(such as binary search trees) will

define those methods based on

specific characteristics

BinaryTree is still useful in certain

situations

16.4 – javafoundations.BTNode //******************************************************************* // BTNode.java Java Foundations // // Represents a node in a binary tree with a left and right child. // Therefore this class also represents the root of a subtree. //******************************************************************* package javafoundations; public class BTNode { protected T element; protected BTNode left, right; //----------------------------------------------------------------- // Creates a new tree node with the specified data. //----------------------------------------------------------------- public BTNode (T element) { this.element = element; left = right = null; } (more…) 16.4 – javafoundations.BTNode //----------------------------------------------------------------- // Returns the element stored in this node. //----------------------------------------------------------------- public T getElement() { return element; } //----------------------------------------------------------------- // Sets the element stored in this node. //----------------------------------------------------------------- public void setElement (T element) { this.element = element; } //----------------------------------------------------------------- // Returns the left subtree of this node. //----------------------------------------------------------------- public BTNode getLeft() { return left; } (more…)

16.4 – javafoundations.BTNode //----------------------------------------------------------------- // Sets the left child of this node. //----------------------------------------------------------------- public void setLeft (BTNode left) { this.left = left; } //----------------------------------------------------------------- // Returns the right subtree of this node. //----------------------------------------------------------------- public BTNode getRight() { return right; } //----------------------------------------------------------------- // Sets the right child of this node. //----------------------------------------------------------------- public void setRight (BTNode right) { this.right = right; } (more…) 16.4 – javafoundations.BTNode //----------------------------------------------------------------- // Returns the element in this subtree that matches the // //----------------------------------------------------------------- specified target. Returns null if the target is not found. public BTNode find (T target) { BTNode result = null; if (element.equals(target)) result = this; else { if (left != null) result = left.find(target); if (result == null && right != null) result = right.find(target); } return result; } (more…) 16.4 – javafoundations.BTNode //----------------------------------------------------------------- // Returns the number of nodes in this subtree. //----------------------------------------------------------------- public int count() { int result = 1; if (left != null) result += left.count(); if (right != null) result += right.count(); return result; } (more…) 16.4 – javafoundations.BTNode //----------------------------------------------------------------- // Performs an inorder traversal on this subtree, updating the // //----------------------------------------------------------------- specified iterator. public void inorder (ArrayIterator iter) { if (left != null) left.inorder (iter); iter.add (element); if (right != null) right.inorder (iter); } //----------------------------------------------------------------- // The following methods are left as programming projects. //----------------------------------------------------------------- // public void preorder (ArrayIterator iter) { } // public void postorder (ArrayIterator iter) { } }

16.4 – javafoundations.LinkedBinaryTree //----------------------------------------------------------------- // Populates and returns an iterator containing the elements in // //----------------------------------------------------------------- this binary tree using a levelorder traversal. public Iterator levelorder() { LinkedQueue<BTNode> ArrayIterator iter =queue = new LinkedQueue<BTNode>(); new ArrayIterator(); if (root != null) { queue.enqueue(root); while (!queue.isEmpty()) { BTNode current = queue.dequeue(); iter.add (current.getElement()); if (current.getLeft() != null) queue.enqueue(current.getLeft()); if (current.getRight() != null) }^ queue.enqueue(current.getRight()); } }^ return^ iter; (more…) 16.4 – javafoundations.LinkedBinaryTree //----------------------------------------------------------------- // Satisfies the Iterable interface using an inorder traversal. //----------------------------------------------------------------- public Iterator iterator() { return inorder(); } //----------------------------------------------------------------- // The following methods are left as programming projects. //----------------------------------------------------------------- // public LinkedBinaryTree getRight() { } // public boolean contains (T target) { } // public boolean isEmpty() { } // public String toString() { } // public Iterator preorder() { } // public Iterator postorder() { } } 16.5 – Decision Trees

A decision tree is a tree whose nodes represent decision points,

and whose children represent the options available

The leaves of a decision tree represent the possible conclusions

that might be drawn based on the answers

Decision trees are sometimes used in expert systems – software

that attempts to represent the knowledge of an expert in a particular

field

A simple decision tree, with yes/no questions,

can be modeled by a binary tree

Expertise examples

 a doctor

 a car mechanic

 accountant

 PC help desk!?!?

16.5 – A Decision Tree for Diagnosing Back Pain

The left child represents the answer “No”

The right child represents the answer “Yes”

16.5 – BackPainAnalyzer.java //******************************************************************** // BackPainAnalyzer.java Java Foundations // // Demonstrates the use of a binary tree. //******************************************************************** public class BackPainAnalyzer { //----------------------------------------------------------------- // Asks questions of the user to diagnose a medical problem. //----------------------------------------------------------------- public static void main (String[] args) { BackPainExpert expert = new BackPainExpert(); expert.diagnose(); } } 16.5 – BackPainExpert.java //******************************************************************** // BackPainExpert.java Java Foundations // //******************************************************************** Represents a simple expert system for back pain diagnosis. import javafoundations.*; public class BackPainExpert { private LinkedBinaryTree tree; //----------------------------------------------------------------- // Sets up the diagnosis question tree. //----------------------------------------------------------------- public BackPainExpert() { String e1 = "Did the pain occur after a blow or jolt?"; String e2 = "Do you have a fever?"; String e3 = "Do you have difficulty controlling your arms or legs?"; String e4 = "Do you have persistent morning stiffness?"; (etc) n7 = new LinkedBinaryTree(e7); n2 = new LinkedBinaryTree(e2, n4, n5); n3 = new LinkedBinaryTree(e3, n6, n7); tree = new LinkedBinaryTree(e1, n2, n3); } 16.5 – BackPainExpert.java //----------------------------------------------------------------- // Follows the diagnosis tree based on user responses. //----------------------------------------------------------------- public void diagnose() { Scanner scan = new Scanner(System.in); LinkedBinaryTree current = tree; System.out.println ("So, you're having back pain."); while (current.size() > 1) { System.out.println (current.getRootElement()); if (scan.nextLine().equalsIgnoreCase("N")) current = current.getLeft(); else current = current.getRight(); } System.out.println (current.getRootElement()); } }