代码拉取完成,页面将自动刷新
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);
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。