-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1490-clone-n-ary-tree.js
53 lines (48 loc) · 1.12 KB
/
1490-clone-n-ary-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val === undefined ? 0 : val;
* this.children = children === undefined ? [] : children;
* };
*/
/**
* @param {Node} node
* @return {Node}
*/
const cloneTree = function(root) {
if(root == null) return null
let node = new Node(root.val)
for(let i = 0, len = root.children.length; i < len; i++) {
node.children.push(cloneTree(root.children[i]))
}
return node
};
// another
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val === undefined ? 0 : val;
* this.children = children === undefined ? [] : children;
* };
*/
/**
* @param {Node} node
* @return {Node}
*/
const cloneTree = function(root) {
if (root === null) return null
const Q = []
const rootCopy = new Node(root.val)
Q.push([root, rootCopy])
while (Q.length) {
const temp = Q.shift()
const node = temp[0]
const copy = temp[1]
node.children.forEach((child) => {
const copyChild = new Node(child.val)
copy.children.push(copyChild)
Q.push([child, copyChild])
})
}
return rootCopy
};