Download presentation
Presentation is loading. Please wait.
Published byRudolph Golden Modified over 6 years ago
1
COMP 103 Tree Traversals Lindsay Groves 2016-T2 Lecture 22
Marcus Frean, Lindsay Groves, Peter Andreae, and Thomas Kuehne VUW Lindsay Groves School of Engineering and Computer Science, Victoria University of Wellington 2016-T2 Lecture 22
2
RECAP-TODAY RECAP Building and traversing general trees
Recursive depth-first traversal TODAY Depth-First vs Breadth-First Traversal Iterative traversals using stacks and queues Bounded depth-first search and iterative deepening Best-first search Chapter 16.2
3
Depth-first Traversal, recursively
e.g., list all employee names Use recursion (and iteration to step through the children) public void listAll() { System.out.println(this.name); // Visit the root for (OrgTreeNode child : this.children) child.listAll(); // Visit the children } Can also be done using recursion.
4
Managing Depth-First Traversal
Need to remember what nodes are still being worked on, and which of their children have been processed already In a recursive depth-first traversal (eg. "ListAll" from earlier), activation stacks and loop control take care of the bookkeeping! When doesn’t this work? A B D E C H G M I K F L J A print own name process children... return B print own name process children... return D print own name process children... return …
5
Breadth-first Traversal
What about printing the nodes by level? root first then second level, then third level, …. Or find the shallowest node with a given value. A B Julie Jenny D E F C Jenny Jude Jiles I…. A B D E C H G M I K F L J
6
Tracking State during Breadth-First Traversal
What nodes do we have to remember? Which order do we work on them? A B D E C H G M I K F L J
7
Breadth-first Traversal: Use a Queue!
public void BreadthFirstTraversal(TreeNode root) { Queue<TreeNode> todo = new LinkedList<TreeNode>(); todo.offer(root); // add while (!todo.isEmpty()) { TreeNode node = todo.poll(); // remove System.out.println(node.name()); for (TreeNode child : node.getChildren()) todo.offer(child); } Look Ma’, no recursion! A B D E C H G M I K F L J
8
Tracking State during Depth-First Traversal
What nodes do we have to remember? Which order do we work on them? A B D E C H G M I K F L J
9
Depth-First Traversal: Use a Stack!
public void DepthFirstTraversal(TreeNode root) { Stack <TreeNode> todo = new Stack<TreeNode>(); todo.push(root); // add while (!todo.isEmpty()) { TreeNode node = todo.pop(); // remove System.out.println(node.name()); for (TreeNode child : node.getChildren()) todo.push(child); } Which traversal order does this implement? Look Ma’, no recursion! A B D E C H G M I K F L J
10
Iterator for binary (search) trees
Iterator keeps a stack of nodes on current path Stop when stack is empty To get next node: (outline!) If current node is a leaf, delete it Else push its children onto the stack (NOTE: This is just a brief note added as a hint because it’s in the assignment, not intended as a detailed explanation!)
11
In-order Traversal, iteratively?
H B A C F I E G
12
Depth-First vs Breadth-First
Visit one child and all of its descendants before its siblings May visit root before, after, or between its children + Requires only one branch to manage traversal! − May find “costly” results first, and may not find results at all (infinite search trees) Breadth-First (level-order): Visit nodes in order of increasing depth May choose nodes in a level in a specific order − Requires accumulation of levels to manage traversal + Finds minimal solutions and guarantees success!
13
Cost of tree traversals
For an n-ary tree of height h: Depth-first traversal stores up to h nodes Just on branch from root to current node Breadth- first traversal stores up to nh nodes! All nodes on all levels to current node Impractical for large n. Can we do better?
14
Depth-first search public TreeNode<E> find(E item) { }
Like depth-first traversal, except we stop on finding a node with the value we’re looking for Or more generally with a node satisfying a given search criterion – see discussion of comparators This version returns the node found, and null if not found public TreeNode<E> find(E item) { if (this.value == item ) return this; for (TreeNode<E> child : this.children) TreeNode<E> r = child.find(item); if ( r ) return r; return null; }
15
Bounded depth-first search
Limit the depth to which a dfs will go Pass max depth as an extra argument decrease on each recursive call exit when it reaches zero public TreeNode<E> find(E item, int n) { if ( n == 0 ) return null; if (this.value == item ) return this; for (TreeNode<E> child : this.children) TreeNode<E> r = child.find(item, n-1); if ( r ) return r; return null; }
16
Iterative deepening for ( int d = 1; d++; d <= max ) }
Use bounded dfs with bigger and bigger bound Guaranteed to find shortest path Still only needs to store h nodes for current path Number of nodes at next level is equal to number of nodes at all earlier levels, so cost of revisiting them is not significant! public TreeNode<E> find(E item) { for ( int d = 1; d++; d <= max ) TreeNode<E> r = child.find(item, d); if ( r ) return r; return null; }
17
Best-first search Suppose we want to find the cheapest path to a node with a given value, where we have costs associated with edges, and cost of a path is the sum of the edge costs. At each step, we want to explore the node with the least cost so far, rather than the newest/oldest as in dfs/bfs. How can we modify our search algorithm to achieve this? Can we use a suitable data structure to make this efficient?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.