← PayPal bank

PayPal · Question 64 · Trees

Populating Next Right Pointers in Each Node

TreesJavacode⏱ O(n)💾 O(1)
Product-based

Problem

Populate each next pointer to point to its next right node in a perfect binary tree.

Approach

Use level order traversal or constant space approach. (Constant Space): walk each level via next links.

Time O(n)Space O(1)

How it works

  1. 1Each level is already linked when its children wire up.
  2. 2Left child points to right sibling; right reaches across via parent next.

Sample input / output

Input:
root = [1, 2, 3, 4, 5, 6, 7]
Output:
[4, 5, 6, 7]

Constraints

Perfect binary tree; 0 <= nodes <= 4095; O(1) extra space.

Solution — read it, then walk it

Time O(n)Space O(1)Loops 3Branches 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class TreeLinkNodeDEFINE valTreeLinkNode left, right,nextTreeLinkNode(int v) { val =v; }DEFINE static voidconnect(TreeLinkNode root)if (root == null)returnTreeLinkNode leftmost =rootwhile (leftmost.left!= null)TreeLinkNode head =leftmostwhile (head != null)head.left.next = head.rightif (head.next != null)head.right.next =head.next.lefthead = head.nextleftmost = leftmost.leftDEFINE static voidmain(String[] args)TreeLinkNode n1 = newTreeLinkNode(1)TreeLinkNode n2 = newTreeLinkNode(2)TreeLinkNode n3 = newTreeLinkNode(3)TreeLinkNode n4 = newTreeLinkNode(4)TreeLinkNode n5 = newTreeLinkNode(5)TreeLinkNode n6 = newTreeLinkNode(6)TreeLinkNode n7 = newTreeLinkNode(7)n1.left = n2; n1.right = n3n2.left = n4; n2.right = n5n3.left = n6; n3.right = n7connect(n1)StringBuilder sb = newStringBuilder("[")TreeLinkNode c = n4while (c != null)sb.append(c.val)c = c.nextsb.append(c != null ? ", ": "")System.out.println(sb.append("]").toString())END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/37

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits