思路
代码实现(java)
/*
// Definition for a Node.
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;
}
};
*/
/**
* Definition for a binary tree node.
* public 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) {
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;
// 创建头结点,将二叉树的左孩子传入,创建N叉树的孩子节点
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;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(root));