ð 117. å¡«å æ¯äžªèç¹çäžäžäžªå³äŸ§èç¹æé II
2022幎10æ10æ¥
- algorithm
ð 117. å¡«å æ¯äžªèç¹çäžäžäžªå³äŸ§èç¹æé II
éŸåºŠ: ð
é®é¢æè¿°
è§£æ³ 1 - å±åº
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
// æè·¯ïŒ
// å±åº - èŸ
å© éå
if(root == null) {
return root;
}
LinkedList<Node> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
int len = queue.size();
Node pre = null;
for(int i = 0; i < len; i ++) {
Node cur = queue.poll();
if(pre != null) {
pre.next = cur;
}
pre = cur;
if(cur.left != null) {
queue.offer(cur.left);
}
if(cur.right != null) {
queue.offer(cur.right);
}
}
}
return root;
}
}
èŸåº 1
è§£æ³ 2 - è¿ä»£
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
// æè·¯ïŒ
// è¿ä»£ - 绎æ€äžäžå±çè¿æ¥å
³ç³»
if(root == null) {
return root;
}
Node topFirst = root;
while(topFirst != null) {
Node cur = topFirst; // åœåå±éŠèç¹
Node secondFirst = new Node(-1); // å建äžäžå±èæéŠèç¹
Node secondCur = secondFirst;
while(cur != null) {
if(cur.left != null) {
// äžäžå±éŸè¡šè¿æ¥åœå left
secondCur.next = cur.left;
secondCur = secondCur.next;
}
if(cur.right != null) {
secondCur.next = cur.right;
secondCur = secondCur.next;
}
cur = cur.next;
}
// è³æ€ïŒåœåå±çäžäžå±èç¹å·²ç»å
šéšè¿æ¥å®æ¯ïŒè·³èœ¬å°äžäžå±
topFirst = secondFirst.next;
}
return root;
}
}