/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// Traverse by level, reverse the list.
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
ArrayList<ArrayList<Integer>> tempList = new ArrayList<ArrayList<Integer>>();
queue.add(root);
while(!queue.isEmpty()){
ArrayList<Integer> level = new ArrayList<Integer>();
tempList.add(level);
int queueSize = queue.size();
for (int i=0; i<queueSize; i++){
TreeNode node = queue.remove();
level.add(node.val);
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}
}
for (int i=tempList.size()-1; i>=0; i--){
result.add(tempList.get(i));
}
return result;
}
}
Binary Tree Level Order Traversal II
最新推荐文章于 2019-05-28 11:08:57 发布