File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(N + E) Node + Edge
2+ // Space Complexity: O(N + E)
3+
4+ var cloneGraph = function ( node ) {
5+ // to keep track of all the nodes that have already been copied
6+ const map = new Map ( ) ;
7+
8+ // helper to perform the deep copy
9+ const dfs = ( currentNode ) => {
10+ if ( ! currentNode ) return null ;
11+
12+ // if the node has already been copied, return the copied one
13+ if ( map . has ( currentNode ) ) return map . get ( currentNode ) ;
14+
15+ // create a new node with the current node's value
16+ const newNode = new Node ( currentNode . val ) ;
17+
18+ // store this new node in the map
19+ map . set ( currentNode , newNode ) ;
20+
21+ // iterate through each neighbor of the current node
22+ for ( const neighbor of currentNode . neighbors ) {
23+ // clone the neighbors and add them to the new node's neighbors
24+ newNode . neighbors . push ( dfs ( neighbor ) ) ;
25+ }
26+
27+ // return the newly created node
28+ return newNode ;
29+ } ;
30+
31+ // start the deep copy from the given node
32+ return dfs ( node ) ;
33+ } ;
You can’t perform that action at this time.
0 commit comments