107. Binary Tree Level Order Tra
2017-10-03 本文已影响0人
namelessEcho
因为要求bottom-up 可以考虑使用一个stack。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root==null)return result;
Stack<List<Integer>> stack = new Stack<>();
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while(!queue.isEmpty())
{
int size = queue.size();
List<Integer> list = new ArrayList<>();
for(int i = 0 ;i<size;i++)
{
TreeNode node = queue.poll();
list.add(node.val);
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
stack.push(list);
}
while(!stack.isEmpty())
{
result.add(stack.pop());
}
return result ;
}
}