Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Populate Next Right Pointers

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Populate Next Right Pointers. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Nykaa's category and recommendation surfaces can represent hierarchical content as a binary tree. Given the root of a binary tree, populate each node's next pointer so it points to the node immediately to its right on the same level. The rightmost node at every level must point to None.

Return the root after modifying the tree in place. The TreeNode class has fields val, left, right, and next; all next pointers are initially None. Do not create a separate queue or list proportional to the tree size.

Formal Specification

  • Input: root, a TreeNode or None.
  • Output: The same root, with all next pointers populated.
  • The tree need not be complete or balanced.
  • For testing, a tree is represented in level order with null for missing children. Output is represented as the values encountered by following next pointers from the first node of each level.

Constraints

  • 0 <= number of nodes <= 10^5
  • -10^9 <= node.val <= 10^9
  • The tree may be incomplete or unbalanced
  • All next pointers are initially None

Function Signature

def connect(root):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output