作者:disappearedgod
时间:2014-5-26
题目
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.
解法
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom1(TreeNode root) {
ArrayList<ArrayList<Integer>> retlist = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> s= new Stack<TreeNode>();
if(root == null)
return retlist;
s.push(root);
list.add(root.val);
while(!s.isEmpty()){
//list.clear();
list = new ArrayList<Integer>();
TreeNode t = s.pop();
if(t!=null){
if(t.left!=null)
{
list.add(t.left.val);
s.push(t.left);
}
if(t.right!=null){
list.add(t.right.val);
s.push(t.right);
}
}
retlist.add(list);
}
ArrayList<ArrayList<Integer>> ret2 = new ArrayList<ArrayList<Integer>>();
for(int i=retlist.size()-1; i>=0; i--){
ret2.add(retlist.get(i));
}
return ret2;
}
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
if(root==null) return result;
Stack<ArrayList<Integer>> stack=new Stack<ArrayList<Integer>>();
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
list.add(root);
while(!list.isEmpty())
{
ArrayList<TreeNode> Tplist=new ArrayList<TreeNode>();
ArrayList<Integer> level=new ArrayList<Integer>();
while(!list.isEmpty())
{
TreeNode node=list.remove(0);
level.add(node.val);
if(node.left!=null) Tplist.add(node.left);
if(node.right!=null) Tplist.add(node.right);
}
stack.push(level);
list=Tplist;
}
while(!stack.isEmpty())
{
result.add(stack.pop());
}
return result;
}
}