Algorithms Homework Assignment 8 JuiShun Lai WeiHsien Chang










- Slides: 10
Algorithms Homework Assignment #8 Jui-Shun Lai, Wei-Hsien Chang
Problem 1 • Consider the problem of finding balance factors in binary trees discussed in class (see slides for “Design by Induction”). Solve this problem using DFS. You need only to define pre. WORK and post. WORK.
Problem 1 (cont. ) • pre. WORK v. height : = 0; v. balance_factor : = 0; • post. WORK v. height : = MAX(v. height, w. height+1); if w = v. leftchild then v. balance_factor : = v. balance_factor + (w. height+1); else if w = v. rightchild then v. balance_factor : = v. balance_factor - (w. height+1);
Problem 3 •
Problem 3 (cont. ) •
Problem 3 (cont. ) 0 • 000 0 1 1 100 0 1 110 0 010 1 0 001 1 101 0 0 111 1 1 011 1
Problem 3 (cont. ) •
Problem 5 • Given a directed acyclic graph G = (V, E), find a simple (directed) path in G that has the maximum number of edges among all simple paths in G. The algorithm should run in linear time. • Algorithm Find. Longest. Path(G) Input: G = (V, E) (a directed acyclic graph) Output: A Stack which records the longest path. vertex [length: the length of the path from a source vertex to the which we are looking at, initial = 0]
Problem 5 (cont. ) O(|V|+|E|) begin Initialize v. Indegree for every vertex v; O(|V|) for all vertices v in V do if v. Indegree = 0 then put v in Queue; repeat remove vertex v from Queue; for all edges (v, w) do if v. length + 1 > w. length then O(|V| + |E|) w. length : = v. length + 1; w. pre : = v; w. Indegree : = w. Indegree -1; if w. Indegree = 0 then put w in Queue; if Queue is empty then vpath : = v; until Queue is empty put vpath on Stack; while vpath has a predecessor do put vpath. pre on Stack; O(|V|) vpath : = vpath. pre; ouput: Stack end //by DFS //begin of a path //update the current longest path //idea of topological sort //used to get the whole path










