LeetCode - Binary Tree Level Order Traversal II

     把上一个类似的题目中的list反转就可以了。

   

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        List<List<Integer>> trlist = new ArrayList<>();
        bfs(0, root, list);
        for(int i=list.size()-1; i>=0; i--) {
            trlist.add(list.get(i));
        }
        return trlist;

    }
    
    public void bfs(int pos, TreeNode root, List<List<Integer>> list) {
        if(root==null) return;
        if(list.size() > pos) {
            list.get(pos).add(root.val);
        }
        else {
            List<Integer> l = new ArrayList<>();
            l.add(root.val);
            list.add(l);
        }
        bfs(pos+1, root.left, list);
        bfs(pos+1, root.right, list);
    }

}

 

posted @ 2015-04-26 21:38  Pickle  阅读(185)  评论(0编辑  收藏  举报