431. 将 N 叉树编码为二叉树
设计一个算法,可以将 N 叉树编码为二叉树,并能将该二叉树解码为原 N 叉树。一个 N 叉树是指每个节点都有不超过 N 个孩子节点的有根树。类似地,一个二叉树是指每个节点都有不超过 2 个孩子节点的有根树。你的编码 / 解码的算法的实现没有限制,你只需要保证一个 N 叉树可以编码为二叉树且该二叉树可以解码回原始 N 叉树即可。
例如,你可以将下面的 3-叉
树以该种方式编码:
注意,上面的方法仅仅是一个例子,可能可行也可能不可行。你没有必要遵循这种形式转化,你可以自己创造和实现不同的方法。
注意:
-
N
的范围在[1, 1000]
- 不要使用类成员 / 全局变量 / 静态变量来存储状态。你的编码和解码算法应是无状态的。
做题结果
成功,这题难的是构思,构思出来了就很简单
方法:DFS
引用评论区一堆人说的话“左孩子,右兄弟”,补个图。
对于左侧多叉数,第一层是 [1],第二层[2,3,4]。那我们把第二层的第一个元素作为本层[1],二叉树的左子树,然后 3,4 节点作为和 2 同层的节点,放在 2 的右子树。
多叉树到二叉树:
1. 现在是根,定义子树前驱节点
2-1. 构建子树,子树有前驱节点,则当前节点是前驱节点的兄弟节点,前驱节点的右指针指向当前元素
2-2. 构建子树,子树没有前驱节点,则说明是本层的第一个元素,父节点的左指针指向它
3. 修改前驱节点
二叉树到多叉树:
1. 现在是根,检查左子树是否为空,非空时构建子树
2. 创建子树并添加到当前的子节点中,不断向二叉树的右子树移动,构造多叉树同层节点
class Codec {
// Encodes an n-ary tree to a binary tree.
public TreeNode encode(Node root) {
if(root == null) return null;
TreeNode t = new TreeNode(root.val);
TreeNode pre = null;
//子树放左边,同层子树一直放置为前一个的右子树
if(root.children!=null){
for(Node v:root.children){
TreeNode inner = encode(v);
if(pre!=null){
pre.right = inner;
}else{
t.left = inner;
}
pre = inner;
}
}
return t;
}
// Decodes your binary tree to an n-ary tree.
public Node decode(TreeNode root) {
if(root == null) return null;
Node n = new Node(root.val);
n.children = new ArrayList<>();
if(root.left!=null){
TreeNode curr = root.left;
while (curr!=null){
Node v = decode(curr);
n.children.add(v);
curr = curr.right;
}
}
return n;
}
}