21 · Tree Traversals

#117 Populating Next Right Pointers in Each Node II

Mediumsolve on LeetCode ↗

frequently reported atBloombergMetaMicrosoftAmazonGoogle

the problem

In plain words

Every node has an extra pointer next. Point it at the node immediately to its right on the same level, or null if it's the last node of its level. The tree can have any shape (not necessarily perfect). Return the root. The node class is Node { int val; Node left, right, next; }.

in root = [1,2,3,4,5,null,7]

out [1,#,2,3,#,4,5,7,#]

Each level read through the next pointers; # ends a level. 5's next is 7, across the gap under 3.

in root = []

out []

  • 0 ≤ number of nodes ≤ 6000
  • -100 ≤ Node.val ≤ 100
  • Follow-up: use only O(1) extra space (the recursion stack doesn't count)

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #199
      Binary Tree Right Side View
      Mediumin Traversals
    2. #102
    3. #21
      Merge Two Sorted Lists
      Easyin Linked Lists