70 - 二叉树的层次遍历 II

5.15

先做的71,在做这个70 ,就无压力了。

就是利用ArrayList(0,tmp)一直在头部进行插入的操作,就可以达到反序的效果。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: buttom-up level order a list of lists of integer
     */
    public ArrayList> levelOrderBottom(TreeNode root) {
        // write your code here
        ArrayList> res = new ArrayList>();
        ArrayList list = new ArrayList();
        if(root == null){
            return res;
        }
        LinkedList queue = new LinkedList();
        TreeNode bt = root;
        TreeNode flag = root;
        queue.addLast(bt);
        while(!queue.isEmpty()){
            bt = queue.pop();
            list.add(bt.val);
            if(bt.left != null){
                queue.addLast(bt.left);
            }
            if(bt.right != null){
                queue.addLast(bt.right);
            }
            if(bt == flag){
                flag = queue.peekLast();
                ArrayList tmp = new ArrayList();
                Iterator ite = list.iterator();
                while(ite.hasNext()){
                    tmp.add((Integer)ite.next());
                }
                res.add(0,tmp);
                list.clear();
            }
        }
        return res;
    }
}


你可能感兴趣的:(lintcode)