/**
* 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) {
LinkedList<List<Integer>> list = new LinkedList<List<Integer>>();
addLevel(list, 0, root);
return list;
}
private void addLevel(LinkedList<List<Integer>> list, int level, TreeNode node) {
if (node == null) return;
if (list.size()-1 < level) list.addFirst(new LinkedList<Integer>());
list.get(list.size()-1-level).add(node.val);
addLevel(list, level+1, node.left);
addLevel(list, level+1, node.right);
}
}
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = [];
if not root:
return res;
res.append([root.val]);
frontier1 = [root];
while(len(frontier1) != 0):
frontier2 = [];
temp = [];
for i in frontier1: #######Explore all the node at current level
v = i;
if v.left:
frontier2.append(v.left);
temp.append(v.left.val);
if v.right:
frontier2.append(v.right);
temp.append(v.right.val);
if temp:
res.append(temp);
frontier1 = frontier2;
return res[::-1]; ###reverse the result list
/**
* 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>> res = new LinkedList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
int curLen = queue.size();
List<Integer> level = new LinkedList<Integer>();
for(int i = 0; i < curLen; i++) {
TreeNode temp = queue.poll();
level.add(temp.val);
if(temp.left != null) queue.offer(temp.left);
if(temp.right != null) queue.offer(temp.right);
}
res.add(0, level);
}
return res;
}
}