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 13 | C++<br />

13 8 Write a method that takes a pointer to a Node structure as a parameter and returns<br />

a complete copy of <strong>the</strong> passed-in data structure The Node structure contains two<br />

pointers to o<strong>the</strong>r Node structures<br />

SOLUTION<br />

2 2 3<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Knowledge Based<br />

pg 76<br />

The algorithm will maintain a mapping from a node address in <strong>the</strong> original structure to <strong>the</strong><br />

corresponding node in <strong>the</strong> new structure This mapping will allow us to discover previously<br />

copied nodes during a traditional depth first traversal of <strong>the</strong> structure (Traversals often mark<br />

visited nodes--<strong>the</strong> mark can take many forms and does not necessarily need to be stored in<br />

<strong>the</strong> node ) Thus, we have a simple recursive algorithm:<br />

1 typedef map NodeMap;<br />

2<br />

3 Node * copy_recursive(Node * cur, NodeMap & nodeMap) {<br />

4 if(cur == NULL) {<br />

5 return NULL;<br />

6 }<br />

7 NodeMap::iterator i = nodeMap.find(cur);<br />

8 if (i != nodeMap.end()) {<br />

9 // we’ve been here before, return <strong>the</strong> copy<br />

10 return i->second;<br />

11 }<br />

12 Node * node = new Node;<br />

13 nodeMap[cur] = node; // map current node before traversing links<br />

14 node->ptr1 = copy_recursive(cur->ptr1, nodeMap);<br />

15 node->ptr2 = copy_recursive(cur->ptr2, nodeMap);<br />

16 return node;<br />

17 }<br />

18 Node * copy_structure(Node * root) {<br />

19 NodeMap nodeMap; // we will need an empty map<br />

20 return copy_recursive(root, nodeMap);<br />

21 }<br />

22

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

Saved successfully!

Ooh no, something went wrong!