File tree 1 file changed +58
-0
lines changed
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments