-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0431-encode-n-ary-tree-to-binary-tree.js
More file actions
46 lines (37 loc) · 1.18 KB
/
0431-encode-n-ary-tree-to-binary-tree.js
File metadata and controls
46 lines (37 loc) · 1.18 KB
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
/**
* Encode N Ary Tree To Binary Tree
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
class Codec {
constructor() { }
encode = function (naryRoot) {
if (!naryRoot) {
return null;
}
const binaryRepresentationRoot = new TreeNode(naryRoot.val);
if (naryRoot.children.length > 0) {
binaryRepresentationRoot.left = this.encode(naryRoot.children[0]);
}
let currentBinaryChild = binaryRepresentationRoot.left;
for (let childIndex = 1; childIndex < naryRoot.children.length; childIndex++) {
if (currentBinaryChild) {
currentBinaryChild.right = this.encode(naryRoot.children[childIndex]);
currentBinaryChild = currentBinaryChild.right;
}
}
return binaryRepresentationRoot;
};
decode = function (binaryRootNode) {
if (!binaryRootNode) {
return null;
}
const naryNodeResult = new _Node(binaryRootNode.val, []);
let currentBinarySiblingPointer = binaryRootNode.left;
while (currentBinarySiblingPointer) {
naryNodeResult.children.push(this.decode(currentBinarySiblingPointer));
currentBinarySiblingPointer = currentBinarySiblingPointer.right;
}
return naryNodeResult;
};
}