Transcript Trees

Trees
Tree Concepts
Previous data organizations place data in
linear order
Some data organizations require
categorizing data into groups, subgroups
This is hierarchical classification
• Data items appear at various levels within the
organization
2
Hierarchical Organization
Example: File directories
Computer files organized into folders.
3
Hierarchical Organization
Example: A university's organization
A university's administrative structure.
4
Hierarchical Organization
Example: Family trees
Carole’s children and grandchildren.
5
Hierarchical Organization
Example: Family trees
Jared’s parents and grandparents.
6
Tree Terminology
A tree is
• A set of nodes (vertices)
• Connected by arcs (edges)
The arcs indicate relationships among
nodes
Nodes arranged in levels
• Indicate the nodes’ hierarchy
• Top level is a single node called the root
7
Tree Terminology
8
Tree Terminology
Nodes at a given level are children of
nodes of previous level
Node with children is the parent node of
those children
Nodes with same parent are siblings
Node with no children is a leaf node
The only node with no parent is the root
node
• All others have one parent each
9
Tree Terminology
Empty trees?
• Some authors specify a general tree must have at
least the root node
• This text will allow all trees to be empty
A node is reached from the root by a path
• The length of the path is the number of arcs that
compose it
The height of a tree is the number of levels in the
tree (alternatively, the number of arcs to a node)
The subtree of a node is a tree rooted at a child
of that node
10
Binary Trees
Each node has at most two children
Three binary trees.
11
Binary Trees
A binary tree is either empty or has the
following form
• Where Tleft and Tright are binary trees
12
Binary Trees
Every non-leaf in a full binary tree has exactly
two children
A complete binary tree is full to its next-to-last
level
• Leaves on last level filled from left to right
The number of nodes in a full binary tree is
n=2h-1 (recall: root is at level (height) 1)*
The height of a binary tree with n nodes that is
either complete or full is thus log2(n + 1)
*Note: for root at depth d=0, n=2d+1-1
13
Binary
Trees
The number of
nodes in a full
binary tree as a
function of the
tree's height.
14
Traversals of a Tree
Visiting a node
• Processing the data within a node
This is the action performed on each node
during traversal of a tree
A traversal can pass through a node
without visiting it at that moment
For a binary tree
• Visit the root
• Visit all nodes in the root’s left subtree
• Visit all nodes in the root’s right subtree
15
Traversals of a Tree
Preorder traversal: visit root before the
subtrees
This is an
example of a
depth-first
traversal.
The visitation order of a preorder traversal.
16
Traversals of a Tree
Inorder traversal: visit root between visiting
the subtrees
The visitation order of an inorder traversal.
17
Traversals of a Tree
Postorder traversal: visit root after visiting
the subtrees
The visitation order of a postorder traversal.
18
Traversals of a Tree
Level-order traversal: begin at the root, visit
nodes one level at a time
This is an
example of a
breadth-first
traversal.
The visitation order of a level-order traversal.
19
Traversals of a General Tree
A general tree has traversals that
are in
• Level order
• Preorder
• Postorder
Inorder traversal not well defined
for a general tree
20
Traversals of a General Tree
The visitation order of two traversals of a general tree:
(a) preorder; (b) postorder.
21
Examples of Binary Trees
Expression Trees
Expression trees for four algebraic expressions.
22
Examples of Binary Trees
Algorithm for evaluating an expression tree
in postorder traversal
Algorithm evaluate(expressionTree)
if (expressionTree is empty)
return 0
else {
firstOperand = evaluate(left subtree of expressionTree)
secondOperand = evaluate(right subtree of expressionTree)
operator = the root of expressionTree
return the result of the operation operator and its operands
firstOperand and secondOperand
}
23
Decision Trees
A decision tree can be the basis of an expert
system
• Helps users solve problems, make decisions
A binary decision tree.
24
Decision Trees
Possible interface for a binary decision tree.
public interface DecisionTreeInterface extends BinaryTreeInterface {
//get the data in the current node
public Object getCurrentData();
//determine whether current node contains an answer (i.e., is a leaf)
public boolean isAnswer();
//move current node to the left (right) child of the current node
public void advanceToNo();
public void advanceToYes();
//set current node to the root of the tree
public void reset();
}
25
Decision Trees
An initial decision tree for a guessing game.
26
Decision Trees
The decision tree for a guessing
game after acquiring another fact.
27
Binary Search Trees
A search tree organizes its data so that a
search is more efficient
Binary search tree
• Nodes contain Comparable objects
• A node's data is greater than the data in the
node's left subtree
• A node's data is less than the data in the
node's right subtree
28
Binary Search Trees
A binary search tree of names.
29
Binary Search Trees
Two binary search trees containing the same names
30
Binary Search Trees
Algorithm for searching a binary search tree
Algorithm bstSearch(binarySearchTree, desiredObject)
// Searches a binary search tree for a given object. Returns true if found.
if (binarySearchTree is empty)
return false
else if (desiredObject = = object in the root of binarySearchTree)
return true
else if (desiredObject < object in the root of binarySearchTree)
return bstSearch(left subtree of binarySearchTree, desiredObject)
else
return bstSearch(right subtree of binarySearchTree, desiredObject)
31
Heaps
A complete binary tree
• Nodes contain Comparable objects
• Each node contains no smaller (or no larger)
than objects in its descendants
Maxheap
• Object in a node is ≥ its descendant objects
Minheap
• Object in a node is ≤ descendant objects
32
Heaps
(a) A maxheap and (b) a minheap
that contain the same values
Consider how to use a heap to implement a priority queue…
33
Examples of General Trees
expression>::=<term> | <term>+<term> |
<term>-<term>
<term>::=<factor> | <factor>*<factor> |
<factor>/<factor>
<factor>::=<variable> | (<expression>)
<variable>::=a | b | … | z | A | B | … | Z
A parse tree for the
algebraic
expression
a * (b + c)
34
Examples of General Trees
A portion of a game tree for tic-tac-toe
35
Java Interfaces for Trees
An interface that specifies operations
common to all trees
public interface TreeInterface {
public Object getRootData();
public int getHeight();
public int getNumberOfNodes();
public boolean isEmpty();
public void clear();
}
36
Java Interfaces for Trees
Interface for iterators for various traversals
import java.util.Iterator;
public interface TreeIteratorInterface {
public Iterator getPreorderIterator();
public Iterator getPostorderIterator();
public Iterator getInorderIterator();
public Iterator getLevelOrderIterator();
}
37
Java Interfaces for Trees
Interface for a class of binary trees
public interface BinaryTreeInterface extends TreeInterface, TreeIteratorInterface{
//Set existing (perhaps just created) binary tree to a new one-node binary tree
public void setTree(Object rootData);
//Set existing (perhaps just created) binary tree to a new binary tree
public void setTree(Object rootData, BinaryTreeInterface leftTree,
BinaryTreeInterface rightTree);
}
38
// represent each leaf as a one-node tree
BinaryTreeInterface dTree = new BinaryTree();
dTree.setTree("D");
BinaryTreeInterface fTree = new BinaryTree();
fTree.setTree("F");
BinaryTreeInterface gTree = new BinaryTree();
gTree.setTree("G");
BinaryTreeInterface hTree = new BinaryTree();
hTree.setTree("H");
BinaryTreeInterface emptyTree = new BinaryTree();
// form larger subtrees
BinaryTreeInterface eTree = new BinaryTree();
eTree.setTree("E", fTree, gTree); // subtree rooted at E
BinaryTreeInterface bTree = new BinaryTree();
bTree.setTree("B", dTree, eTree); // subtree rooted at B
BinaryTreeInterface cTree = new BinaryTree();
cTree.setTree("C", emptyTree, hTree); // subtree rooted at C
BinaryTreeInterface aTree = new BinaryTree();
aTree.setTree("A", bTree, cTree); // desired tree rooted at A
39
// display root, height, number of nodes
System.out.println("Root of tree is " + aTree.getRootData());
System.out.println("Height of tree is " + aTree.getHeight());
System.out.println("Tree has " + aTree.getNumberOfNodes() + " nodes");
// display nodes in preorder
Iterator preorder = aTree.getPreorderIterator();
while (preorder.hasNext())
System.out.print(preorder.next() + " ");
System.out.println();
//note: should write a special print routine
See complete source code…
40