Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0 Star 0 Fork 0

徐云天/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
_117.java 2.33 KB
一键复制 编辑 原始数据 按行查看 历史
徐云天 提交于 2021-07-21 16:26 +08:00 . 增加117
import java.util.ArrayList;
import java.util.List;
public class _117 {
static class Solution1 {
public Node connect(Node root) {
//换成了二叉树,逻辑发生变化
//强制连接右节点,parent,or uncle 无可用,parent = parent.next || uncle = uncle.next;
Node tl = root;
while (tl != null) {
//这里,寻找第一个可用的左侧节点
Node s = null;
while (tl != null && s == null) {
if (tl.left == null && tl.right == null) tl = tl.next;
else {
s = tl.left == null ? tl.right : tl.left;
break;
}
}
Node nextTl = s;
//从s开始不断连接
while (tl != null && s != null) {
if (tl.left == null && tl.right == null) {
tl = tl.next;
continue;
}
if (s == tl.left) {
if (tl.right != null) {
s.next = tl.right;
s = s.next;
}
tl = tl.next;
} else if (s == tl.right) {
tl = tl.next;
} else {
s.next = tl.left == null ? tl.right : tl.left;
s = s.next;
}
}
tl = nextTl;
}
return root;
}
}
static class Solution2 {
public Node connect(Node root) {
//bfs
List<Node> cur = new ArrayList<>();
if (root != null) cur.add(root);
while (cur.size() > 0) {
handleSameLevel(cur);
List<Node> next = new ArrayList<>();
for (Node item : cur) {
if (item.left != null) next.add(item.left);
if (item.right != null) next.add(item.right);
}
cur = next;
}
return root;
}
public void handleSameLevel(List<Node> lv) {
for (int i = 0; i < lv.size() - 1; i++) {
lv.get(i).next = lv.get(i + 1);
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xuyuntian/leetcode.git
git@gitee.com:xuyuntian/leetcode.git
xuyuntian
leetcode
leetcode
master