BFS solution :
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
queue = deque([root])
while queue:
level = deque()
while queue:
node = queue.popleft()
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
for i in range(1, len(level)):
level[i-1].next = level[i]
queue = level
return root
Recursive solution:
/*
// 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) {
if (root.left != null) {
root.left.next = root.right;
}
if (root.right != null && root.next != null) {
root.right.next = root.next.left;
}
connect(root.right);
connect(root.left);
}
return root;
}
}
Iterative solution:
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
tmp = root
while root and root.left:
nxt = root.left
while root:
root.left.next = root.right
root.right.next = root.next.left if root.next else None
root = root.next
root = nxt
return tmp
Edited on 12/29/2021. Replace the recursive solution with Java code solution.
No comments:
Post a Comment