Skip to content

Commit 2e9e92e

Browse files
authored
Create 1516-move-sub-tree-of-n-ary-tree.js
1 parent 9042bf7 commit 2e9e92e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

1516-move-sub-tree-of-n-ary-tree.js

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val, children) {
4+
* this.val = val === undefined ? 0 : val;
5+
* this.children = children === undefined ? [] : children;
6+
* };
7+
*/
8+
9+
/**
10+
* @param {Node} root
11+
* @param {Node} p
12+
* @param {Node} q
13+
* @return {Node}
14+
*/
15+
function moveSubTree(root, p, q) {
16+
for (let node of q.children) {
17+
if (p === node) {
18+
return root
19+
}
20+
}
21+
if (find(p, q)) {
22+
update(root, p, q)
23+
q.children.push(p)
24+
return root === p ? q : root
25+
} else {
26+
update(root, null, p)
27+
q.children.push(p)
28+
return root
29+
}
30+
function update(root, p, q) {
31+
if (root == null) {
32+
return
33+
}
34+
for (let node of root.children) {
35+
update(node, p, q)
36+
}
37+
for (let i = 0; i < root.children.length; i++) {
38+
if (root.children[i] === p) {
39+
root.children[i] = q
40+
} else if (root.children[i] === q) {
41+
root.children.splice(i, 1)
42+
}
43+
}
44+
}
45+
function find(root, t) {
46+
if (root == null) {
47+
return false
48+
}
49+
let ret = root === t
50+
if (ret === true) {
51+
return true
52+
}
53+
for (let node of root.children) {
54+
ret = ret || find(node, t)
55+
}
56+
return ret
57+
}
58+
}

0 commit comments

Comments
 (0)