-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodecNTree.cpp
More file actions
48 lines (42 loc) · 990 Bytes
/
codecNTree.cpp
File metadata and controls
48 lines (42 loc) · 990 Bytes
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
// N-ary Tree:
// 1
// / | \
// 3 2 4
// / \
// 5 6
// Binary Tree:
// 1
// /
// 3
// / \
// 5 2
// \ \
// 6 4
class Codec {
public:
// Encodes an n-ary tree to a binary tree.
TreeNode* encode(Node* root) {
if (!root) return NULL;
TreeNode *res = new TreeNode(root->val);
if (!root->children.empty()) {
res->left = encode(root->children[0]);
}
TreeNode *cur = res->left;
for (int i = 1; i < root->children.size(); ++i) {
cur->right = encode(root->children[i]);
cur = cur->right;
}
return res;
}
// Decodes your binary tree to an n-ary tree.
Node* decode(TreeNode* root) {
if (!root) return NULL;
Node *res = new Node(root->val, {});
TreeNode *cur = root->left;
while (cur) {
res->children.push_back(decode(cur));
cur = cur->right;
}
return res;
}
};