当前位置:网站首页>431. 将 N 叉树编码为二叉树 DFS
431. 将 N 叉树编码为二叉树 DFS
2022-07-01 03:27:00 【钰娘娘】
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;
}
}边栏推荐
- [reach out to Party welfare] developer reload system sequence
- Addition without addition, subtraction, multiplication and division
- idea插件备份表
- Leetcode:829. 连续整数求和
- Pyramid scene parsing network [pspnet] thesis reading
- Blueprism registration, download and install -rpa Chapter 1
- 241. 为运算表达式设计优先级
- 【伸手党福利】JSONObject转String保留空字段
- 在线公网安备案保姆级教程【伸手党福利】
- 5、【WebGIS实战】软件操作篇——服务发布及权限管理
猜你喜欢
随机推荐
389. find a difference
ASGNet论文和代码解读2
IPv4 and IPv6, LAN and WAN, gateway, public IP and private IP, IP address, subnet mask, network segment, network number, host number, network address, host address, and IP segment / number - what does
TEC: Knowledge Graph Embedding with Triple Context
报错:Plug-ins declaring extensions or extension points must set the singleton directive to true
Leetcode: offer 59 - I. maximum value of sliding window
还在浪费脑细胞自学吗,这份面试笔记绝对是C站天花板
6. Z 字形变换
[TA frost wolf \u may- hundred people plan] 2.4 traditional empirical lighting model
166. fractions to decimals
[daily training] 1175 Prime permutation
Promql select time series
jeecgboot输出日志,@Slf4j的使用方法
[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理
Research on target recognition and tracking based on 3D laser point cloud
4、【WebGIS实战】软件操作篇——数据导入及处理
【EI会议】2022年第三届纳米材料与纳米技术国际会议(NanoMT 2022)
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
241. Design priorities for operational expressions
171. Excel 表列序号










