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.
public class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root != null){ Queue<TreeNode> topLevel = new LinkedList<TreeNode>(); topLevel.add(root); while(topLevel.peek() != null){ Queue<TreeNode> nextLevel = new LinkedList<TreeNode>(); List<Integer> value = new ArrayList<Integer>(); while(topLevel.peek() != null){ TreeNode node = topLevel.poll(); value.add(node.val); if(node.left != null) nextLevel.add(node.left); if(node.right != null) nextLevel.add(node.right); } result.add(0, value); topLevel = nextLevel; } } return result; } }