trees. 2 tree concepts previous data organizations place data in linear order some data...

40
Trees

Upload: eugenia-alexander

Post on 21-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

Trees

2

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

3

Hierarchical Organization

Example: File directories

Computer files organized into folders.

4

Hierarchical Organization

Example: A university's organization

A university's administrative structure.

5

Hierarchical Organization

Example: Family trees

Carole’s children and grandchildren.

6

Hierarchical Organization

Example: Family trees

Jared’s parents and grandparents.

7

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

8

Tree Terminology

9

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

10

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

11

Binary Trees

Each node has at most two children

Three binary trees.

12

Binary Trees

A binary tree is either empty or has the following form

• Where Tleft and Tright are binary trees

13

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

14

Binary Trees

The number of nodes in a full

binary tree as a function of the tree's height.

15

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 treeA traversal can pass through a node without visiting it at that momentFor a binary tree• Visit the root• Visit all nodes in the root’s left subtree• Visit all nodes in the root’s right subtree

16

Traversals of a Tree

Preorder traversal: visit root before the subtrees

The visitation order of a preorder traversal.

This is an example of a

depth-first traversal.

This is an example of a

depth-first traversal.

17

Traversals of a Tree

Inorder traversal: visit root between visiting the subtrees

The visitation order of an inorder traversal.

18

Traversals of a Tree

Postorder traversal: visit root after visiting the subtrees

The visitation order of a postorder traversal.

19

Traversals of a Tree

Level-order traversal: begin at the root, visit nodes one level at a time

The visitation order of a level-order traversal.

This is an example of a breadth-first

traversal.

This is an example of a breadth-first

traversal.

20

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

21

Traversals of a General Tree

The visitation order of two traversals of a general tree: (a) preorder; (b) postorder.

22

Examples of Binary Trees

Expression Trees

Expression trees for four algebraic expressions.

23

Examples of Binary TreesAlgorithm for evaluating an expression tree in postorder traversal

Algorithm evaluate(expressionTree)if (expressionTree is empty)

return 0else {

firstOperand = evaluate(left subtree of expressionTree)secondOperand = evaluate(right subtree of expressionTree)operator = the root of expressionTreereturn the result of the operation operator and its operands

firstOperand and secondOperand}

24

Decision TreesA decision tree can be the basis of an expert system• Helps users solve problems, make decisions

A binary decision tree.

25

Decision TreesPossible interface for a binary decision tree.

public interface DecisionTreeInterface extends BinaryTreeInterface {//get the data in the current nodepublic 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 nodepublic void advanceToNo();public void advanceToYes();

//set current node to the root of the treepublic void reset();

}

26

Decision Trees

An initial decision tree for a guessing game.

27

Decision Trees

The decision tree for a guessing game after acquiring another fact.

28

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

29

Binary Search Trees

A binary search tree of names.

30

Binary Search Trees

Two binary search trees containing the same names

31

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 falseelse if (desiredObject = = object in the root of binarySearchTree)

return trueelse if (desiredObject < object in the root of binarySearchTree)

return bstSearch(left subtree of binarySearchTree, desiredObject)else

return bstSearch(right subtree of binarySearchTree, desiredObject)

32

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

33

Heaps

(a) A maxheap and (b) a minheap that contain the same values

Consider how to use a heap to implement a priority queue…

34

Examples of General Trees

A parse tree for the algebraic

expression a * (b + c)

expression>::=<term> | <term>+<term> |

<term>-<term>

<term>::=<factor> | <factor>*<factor> |

<factor>/<factor>

<factor>::=<variable> | (<expression>)

<variable>::=a | b | … | z | A | B | … | Z

35

Examples of General Trees

A portion of a game tree for tic-tac-toe

36

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();

}

37

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();

}

38

Java Interfaces for TreesInterface 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 treepublic void setTree(Object rootData, BinaryTreeInterface leftTree,

BinaryTreeInterface rightTree); }

39

// represent each leaf as a one-node treeBinaryTreeInterface 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 subtreesBinaryTreeInterface 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

40

// display root, height, number of nodesSystem.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 preorderIterator preorder = aTree.getPreorderIterator();while (preorder.hasNext())

System.out.print(preorder.next() + " "); //note: should write a special print routineSystem.out.println();

See complete source code…