题目链接这里
这个题和Binary Tree Level Order Traversal这个题是一样的解决方法。只不过我吧他之前的结果链表变成一个栈。然后在程序的最后一次去除然后在发到一个链表里面而已。
/**
* 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) {
TreeNode endLineFlag=new TreeNode(0);
Stack<List<Integer>> myStack= new Stack<List<Integer>> ();
LinkedList<Integer> workContiner=new LinkedList<Integer>();
ArrayDeque<TreeNode> queue=new ArrayDeque<TreeNode>();
if(root==null)
{
return new LinkedList<List<Integer>> ();
}
queue.addLast(root);
queue.addLast(endLineFlag);
TreeNode current=null;
while(queue.size()>1)
{
current=queue.remove();
if(current==endLineFlag)
{
myStack.push(workContiner);
workContiner=new LinkedList<Integer>();
queue.addLast(endLineFlag);
continue;
}
workContiner.add(current.val);
if(current.left!=null)
{
queue.add(current.left);
}
if(current.right!=null)
{
queue.add(current.right);
}
}
myStack.push(workContiner);
List<List<Integer>> resultArray= new LinkedList<List<Integer>> ();
while(!myStack.isEmpty())
{
resultArray.add(myStack.pop());
}
return resultArray;
}
}