Skip to content

Commit 5aa5218

Browse files
authored
Update 1490-clone-n-ary-tree.js
1 parent ef39957 commit 5aa5218

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

1490-clone-n-ary-tree.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,36 @@ const cloneTree = function(root) {
1818
}
1919
return node
2020
};
21+
22+
// another
23+
24+
/**
25+
* // Definition for a Node.
26+
* function Node(val, children) {
27+
* this.val = val === undefined ? 0 : val;
28+
* this.children = children === undefined ? [] : children;
29+
* };
30+
*/
31+
32+
/**
33+
* @param {Node} node
34+
* @return {Node}
35+
*/
36+
const cloneTree = function(root) {
37+
if (root === null) return null
38+
const Q = []
39+
const rootCopy = new Node(root.val)
40+
Q.push([root, rootCopy])
41+
while (Q.length) {
42+
const temp = Q.shift()
43+
const node = temp[0]
44+
const copy = temp[1]
45+
node.children.forEach((child) => {
46+
const copyChild = new Node(child.val)
47+
copy.children.push(copyChild)
48+
Q.push([child, copyChild])
49+
})
50+
}
51+
52+
return rootCopy
53+
};

0 commit comments

Comments
 (0)