FastPrepBinary Tree Level Order Traversal

Binary Tree Level Order Traversal

Google logoGoogle● MediumFULLTIMEINTERNONSITE INTERVIEW
Learn

Problem statement

Given the root of a binary tree, return its node values grouped by depth from top to bottom. Values within each level must appear from left to right. Return an empty list for an empty tree.

Function

levelOrder(root: TreeNode) → List<List<Integer>>

Examples

Example 1

root = [3,9,20,null,null,15,7]return = [[3],[9,20],[15,7]]

The root forms level zero, its two children form level one, and nodes 15 and 7 form level two.

Example 2

root = [1,null,2,3]return = [[1],[2],[3]]

Each node occupies a separate depth even though the tree is skewed.

Example 3

root = []return = []

An empty tree has no levels.

Constraints

  • The tree contains at most 100000 nodes.
  • Each node value is between -10^9 and 10^9.

More Google problems

See Google hiring insights
public List<List<Integer>> levelOrder(TreeNode root) {
    // Write your code here.
}
root[3,9,20,null,null,15,7]
expected[[3],[9,20],[15,7]]
Checking account…