oneby7

Binary Trees Breadth first: level by level

374. Binary Tree Level Order Traversal II

Medium

You are given root, the root node of a binary tree. Return the values of its nodes level by level, starting from the bottom: a list with one list for each level, deepest level first and the root's level last. Each level's list still holds the values of that level's nodes from left to right.

The root is the only node on the first level. Its children make up the second level, their children the third, and so on. A node's level depends only on how far it is from the root, so a leaf high up in the tree stays on its own level. An empty tree has no levels, so the answer is [].

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

-714386102

Input: root = [3, -7, 10, null, 4, 8, 2, 1, null, null, 6]

Output: [[1,6],[4,8,2],[-7,10],[3]]

Explanation: The deepest level holds 1 and 6, so it comes first. Then come 4, 8 and 2, then −7 and 10, and the root 3 is last. 2 is a leaf, but it stays with 4 and 8, the other nodes on its level.

Example 2

Input: root = []

Output: []

Explanation: The tree has no nodes, so it has no levels.

Example 3

−10⁹010⁹

Input: root = [-1000000000, null, 1000000000, 0]

Output: [[0],[1000000000],[-1000000000]]

Explanation: Each node has one child, so every level holds one node, and the answer reads the path from the bottom up.

Check your understanding

Work out the answer for this input before you write any code.

root = [6, -2, 8, 1, null, 5, 3, null, 4]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.