/107. Binary Tree Level Order Traversal II

107. Binary Tree Level Order Traversal II

Medium
Trees67.8% acceptance

Given the root node of a binary tree, return a list of lists containing the values of the nodes grouped by their depth, starting from the deepest level up to the root. Each inner list should contain the values of nodes at the same depth, ordered from left to right.

Example 1

Input: TreeNode(5, TreeNode(2), TreeNode(8, TreeNode(7), TreeNode(10)))

Output: [[7,10],[2,8],[5]]

Explanation: Level 2: [7,10], Level 1: [2,8], Level 0: [5]

Example 2

Input: TreeNode(4, TreeNode(1, None, TreeNode(3)), TreeNode(6))

Output: [[3],[1,6],[4]]

Explanation: Level 2: [3], Level 1: [1,6], Level 0: [4]

Example 3

Input: None

Output: []

Explanation: Empty tree returns empty list.

Constraints

  • 0 <= number of nodes <= 2000
  • -1000 <= node value <= 1000
Python (current runtime)

Case 1

Input: TreeNode(12, TreeNode(9, None, TreeNode(11)), TreeNode(15, TreeNode(14), None))

Expected: [[11,14],[9,15],[12]]

Case 2

Input: TreeNode(7)

Expected: [[7]]

Case 3

Input: TreeNode(1, TreeNode(2, TreeNode(3)), None)

Expected: [[3],[2],[1]]