LeetCode OJ 107. Binary Tree Level Order Traversal II

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,#,#,15,7},

    3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new LinkedList<List<Integer>>();
if(root == null) return list; Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
Queue<TreeNode> queue2 = new LinkedList<TreeNode>(); queue1.offer(root); while(queue1.size()>0){
List<Integer> childlist = new ArrayList<Integer>();
while(queue1.size()>0){
TreeNode node = queue1.remove();
childlist.add(node.val);
if(node.left!=null) queue2.offer(node.left);
if(node.right!=null) queue2.offer(node.right);
}
list.add(0, childlist);
Queue<TreeNode> temp = queue1;
queue1 = queue2;
queue2 = temp;
} return list;
}
}
上一篇:poj 1019


下一篇:DelayedOperationPurgatory之DelayedOperation pool