You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node { int val; Node *left; Node *right; Node *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Input: root = []
Output: []
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if not root:
return root
queue=[]
queue.append(root)
while queue:
temp=[]
while queue:
cur_node=queue.pop(0)
if cur_node.left:
temp.append(cur_node.left)
if cur_node.right:
temp.append(cur_node.right)
for i in range(len(temp)-1):
temp[i].next=temp[i+1]
queue.extend(temp)
return root
print(queue)
There is simple rule for populating next right pointers in each node.
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if not root:
return root
def bfs(root):
# if the node has child
if root.left:
# leftchild.next=parent.right
root.left.next=root.right
# rightchild.next=parent.next.left
if root.next:
root.right.next=root.next.left
# repeat the process with left&right child
bfs(root.left)
bfs(root.right)
bfs(root)
return root
References
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1849143/Python-Easy-Solution-or-BFS-Traversal