因为要求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 ;
}
}
网友评论