ð 116. å¡«å æ¯äžªèç¹çäžäžäžªå³äŸ§èç¹æé
2022幎10æ10æ¥
- algorithm
ð 116. å¡«å æ¯äžªèç¹çäžäžäžªå³äŸ§èç¹æé
éŸåºŠ: ð
é®é¢æè¿°
è§£æ³ 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) {
// æè·¯ïŒ
// éåœ
// ç±äºäžºå®çŸäºåæ ïŒææå¶åèç¹åšåäžå±ïŒå¯ä»¥å©çšè¿äžç¹
return mySol(root);
}
private Node mySol(Node root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return root;
}
if(root.left != null) {
// ç±äºå¶åèç¹åšåäžå±ïŒé£ä¹å·Šåæ é空ïŒæå³çå³åæ ä¹å¿
å®é空
root.left.next = root.right;
// å€ææ¯åŠäžºæå³äŸ§èç¹
if(root.next != null) {
root.right.next = root.next.left;
}
mySol(root.left);
mySol(root.right);
}
return root;
}
}