一、题目
1、题目描述
Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.
For example, you may encode the following 3-ary tree to a binary tree in this way:
Input: root = [1,null,3,2,4,null,5,6]
Note that the above is just an example which might or might not work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
2、基础框架
public class EncodeNaryTreeToBinaryTree {
public static class Node {
public int val;
public List<Node> children;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Codec {
// Encodes an n-ary tree to a binary tree.
public TreeNode encode(Node root) {
}
// Decodes your binary tree to an n-ary tree.
public Node decode(TreeNode root) {
}
}
}
3、原题链接
二、解题报告
1、思路分析
【题意理解】就是将多叉树转换成二叉树,用二叉树来序列化多叉树。
【思路】将多叉树上 X 节点的所有子孩子放在 X 节点的左树的右边界上,只要能将多叉树转成一种无歧义的二叉树结构就可以。
2、时间复杂度
O ( N ) O(N) O(N)
3、代码详解
public class EncodeNaryTreeToBinaryTree {
public static class Node {
public int val;
public List<Node> children;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Codec {
// Encodes an n-ary tree to a binary tree.
public TreeNode encode(Node root) {
if (root == null) {
return null;
}
TreeNode head = new TreeNode(root.val);
head.left = en(root.children);
return head;
}
private TreeNode en(List<Node> children) {
TreeNode head = null;
TreeNode cur = null;
for (Node child : children) { //遍历孩子节点
TreeNode tNode = new TreeNode(child.val);
if (head == null) { //只有第一个孩子节点会进入这个if条件
head = tNode;
} else {
cur.right = tNode;
}
cur = tNode;
cur.left = en(child.children); //深度优先遍历,当前子节点处理完毕之后再处理下一个孩子
}
return head;
}
// Decodes your binary tree to an n-ary tree.
public Node decode(TreeNode root) {
if (root == null) {
return null;
}
return new Node(root.val, de(root.left));
}
public List<Node> de(TreeNode root) {
List<Node> children = new ArrayList<>();
while (root != null) {
Node cur = new Node(root.val, de(root.left)); //用深度优先的方法反序列化
children.add(cur);
root = root.right;
}
return children;
}
}
}