25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solutions to Chapter 4 | Trees and Graphs<br />

4 8 You are given a binary tree in which each node contains a value Design an algorithm<br />

to print all paths which sum up to that value Note that it can be any path in <strong>the</strong> tree<br />

- it does not have to start at <strong>the</strong> root<br />

SOLUTION<br />

1 3 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Data Structures<br />

pg 54<br />

Let’s approach this problem by simplifying it What if <strong>the</strong> path had to start at <strong>the</strong> root? In that<br />

case, we would have a much easier problem:<br />

Start from <strong>the</strong> root and branch left and right, computing <strong>the</strong> sum thus far on each path<br />

When we find <strong>the</strong> sum, we print <strong>the</strong> current path Note that we don’t stop just because<br />

we found <strong>the</strong> sum Why? Because we could have <strong>the</strong> following path (assume we are<br />

looking for <strong>the</strong> sum 5): 2 + 3 + –4 + 3 + 1 + 2 If we stopped once we hit 2 + 3, we’d miss<br />

several paths (2 + 3 + -4 + 3 + 1 and 3 + -4 + 3 + 1 + 2) So, we keep going along every<br />

possible path<br />

Now, what if <strong>the</strong> path can start anywhere? In that case, we make a small modification On<br />

every node, we look “up” to see if we’ve found <strong>the</strong> sum That is—ra<strong>the</strong>r than asking “does<br />

this node start a path with <strong>the</strong> sum?,” we ask “does this node complete a path with <strong>the</strong> sum?”<br />

1 void findSum(TreeNode head, int sum, ArrayList buffer,<br />

2 int level) {<br />

3 if (head == null) return;<br />

4 int tmp = sum;<br />

5 buffer.add(head.data);<br />

6 for (int i = level;i >- 1; i--){<br />

7 tmp -= buffer.get(i);<br />

8 if (tmp == 0) print(buffer, i, level);<br />

9 }<br />

10 ArrayList c1 = (ArrayList) buffer.clone();<br />

11 ArrayList c2 = (ArrayList) buffer.clone();<br />

12 findSum(head.left, sum, c1, level + 1);<br />

13 findSum(head.right, sum, c2, level + 1);<br />

14 }<br />

15<br />

16 void print(ArrayList buffer, int level, int i2) {<br />

17 for (int i = level; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!