Design Gurus Logo
Level Order Successor (easy)

Problem Statement

Given a root of the binary tree and an integer key, find the level order successor of the node containing the given key as a value in the tree.

The level order successor is the node that appears right after the given node in the level order traversal.

About the return value. Return the successor node itself, not its value. The test harness reads .val from whatever you return to print the result, so returning a plain number, or None, makes it fail with an attribute error. Every test on this question has a real successor.

Examples

Example 1

  • Input: root = [1, 2, 3, 4, 5], key = 3
Image
  • Output: 4
  • Explanation: The level-order traversal of the tree is [1, 2, 3, 4, 5]. The successor of 3 in this order is 4.

Example 2

  • Input: root = [12, 7, 1, 9, null, 10, 5], key = 9
Image
  • Output: 10
  • Explanation: The level-order traversal of the tree is [12, 7, 1, 9, 10, 5]. The successor of 9 in this order is 10.

Example 3

  • Input: root = [12, 7, 1, 9, null, 10, 5], key = 12
Image
  • Output: 7
  • Explanation: The level-order traversal of the tree is [12, 7, 1, 9, 10]. The successor of 12 in this order is 7.

Constraints:

  • The number of nodes in the tree is in the range [0, 10<sup>5</sup>].
  • -1000 <= Node.val <= 1000

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory