27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

4.4 Given a binary search tree, design an algorithm which creates a linked list of all <strong>the</strong><br />

nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists).<br />

SOLUTION<br />

pg 54<br />

We can do a simple level by level traversal of <strong>the</strong> tree, with a slight modification of <strong>the</strong> breathfirst<br />

traversal of <strong>the</strong> tree.<br />

In a usual breath first search traversal, we simply traverse <strong>the</strong> nodes without caring which<br />

level we are on. In this case, it is critical to know <strong>the</strong> level. We thus use a dummy node to<br />

indicate when we have finished one level <strong>and</strong> are starting on <strong>the</strong> next.<br />

1 ArrayList findLevelLinkList(TreeNode root) {<br />

2 int level = 0;<br />

3 ArrayList result =<br />

4 new ArrayList();<br />

5 LinkedList list = new LinkedList();<br />

6 list.add(root);<br />

7 result.add(level, list);<br />

8 while (true) {<br />

9 list = new LinkedList();<br />

10 for (int i = 0; i < result.get(level).size(); i++) {<br />

11 TreeNode n = (TreeNode) result.get(level).get(i);<br />

12 if (n != null) {<br />

13 if(n.left != null) list.add(n.left);<br />

14 if(n.right!= null) list.add(n.right);<br />

15 }<br />

16 }<br />

17 if (list.size() > 0) {<br />

18 result.add(level + 1, list);<br />

19 } else {<br />

20 break;<br />

21 }<br />

22 level++;<br />

23 }<br />

24 return result;<br />

25 }<br />

CareerCup.com<br />

1 2 6

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

Saved successfully!

Ooh no, something went wrong!