about // doc

LeetCode - Binary Tree Level Order Traversal (I and II)

Click here to go back to LeetCode summary page.

Problem description is here, or as follows:

Given a binary tree, return the level order traversal of its 
nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

The definition of level travesal is already explained in the problem description (more like a breadth first search). A queue is utilized here, therefore recursive implementation is not possible (recursive calls use stacks implicitly). The output format of this problem is different from previous inorder/preorder/postorder traversal problems, thus extra code is needed.

A variant of this problem is here, or as follows:

Given a binary tree, return the bottom-up level order traversal of 
its nodes' values (i.e., from left to right, level by level from leaf 
to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

One solution is use most part of the previous binary tree level traversal but insert the level list at the head of the results rather than append it so that an reversal is not needed. There is discussion on the LeetCode forum here. This problem is somewhat redundant.

comments powered by Disqus