107. Binary Tree Level Order Traversal II
Question:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
Example:
For example: Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
[
[15,7],
[9,20],
[3]
]
Source code
Version 1
Idea:
I made a big mistake, I always think the solution that find the deepest depth first, the go back to the root with each layers. I realized an efficient approach until I had refered to Huahua's Tech Road.
You must understand how to implement a two dimensional vector first. Write a function as recursion, store each elements from top of tree. res.size() <= depth
is an important statement to expand 2D vector size. Then, we must go through every left & right nodes and store it based on correspondingly depth. Finaly, let go back to original function, we must use reverse() to pass the answers.
1 | /** |