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).
For example:
Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Thinking
階序走訪(Level Order Traversal)基本上就是利用廣度優先搜尋法(Breadth-first Search),以Queue來實作,但此題要求Bottom-up,因此每算出一層都要把結果放在list的最前頭,這樣順序才會是對的
My C# Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<IList<int>> LevelOrderBottom(TreeNode root) {
var result = new List<IList<int>>();
if (root == null) return result;
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
while(queue.Count > 0)
{
var list = new List<int>();
var currentLevelNumber = queue.Count;
for (var i = 0; i < currentLevelNumber; i++)
{
var node = queue.Dequeue();
list.Add(node.val);
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
result.Insert(0, list);
}
return result;
}
}