Populating Next Right Pointers in Each Node

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
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.
  • -1000 <= node.val <= 1000
# first intuition is BFS traversal and 
# pop the left and point to the node on the 0th element of the tree.
# append all the elements left to right.
"""
# 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':
# first intuition is BFS traversal and
# pop the left and point to the node on the 0th element of the tree.
# append all the elements , also nulls.
if not root:
return root

q = collections.deque()
q.append(root)

while q:
length = len(q)

for i in range(length):
node = q.popleft()

if i < length -1:
node.next = q[0]

if node.left: q.append(node.left)
if node.right: q.append(node.right)

return root
  • Space Complexity: O(N). This is a perfect binary tree which means the last level contains N/2 nodes. The space complexity for breadth first traversal is the space occupied by the queue which is dependent upon the maximum number of nodes in particular level. So, in this case, the space complexity would be O(N).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store