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

徐云天/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
_116.java 2.17 KB
一键复制 编辑 原始数据 按行查看 历史
徐云天 提交于 2021-07-21 14:09 +08:00 . 增加116
import java.util.ArrayList;
import java.util.List;
public class _116 {
static class Solution1 {
public Node connect(Node root) {
dfs(root, null);
return root;
}
public void dfs(Node node, Node parent) {
if (node == null) return;
if (parent != null) {
if (node == parent.left) node.next = parent.right;
else node.next = parent.next == null ? null : parent.next.left;
}
dfs(node.left, node);
dfs(node.right, node);
}
}
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);
}
}
}
static class Solution3 {
public Node connect(Node root) {
Node topLeft = root;
//状态变化
while (topLeft != null) {
Node start = topLeft.left;
int status = 0;//0,连接右节点,1,连接叔节点的左节点
Node nextTopLeft = start;
while (start != null && topLeft != null) {
if (status == 0) {
start.next = topLeft.right;
start = start.next;
topLeft = topLeft.next;
} else {
start.next = topLeft.left;
start = start.next;
}
status = (status + 1) % 2;
}
topLeft = nextTopLeft;
}
return root;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xuyuntian/leetcode.git
git@gitee.com:xuyuntian/leetcode.git
xuyuntian
leetcode
leetcode
master