107. Binary Tree Level Order Traversal II

Given a binary tree, return thebottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

思路:和上一题一样,唯一要改的是list.add(0,xxx)

public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        if (root==null){
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        while(!queue.isEmpty()){
            List<Integer> temp = new ArrayList<Integer>();
            int curL = queue.size();
            for (int i=0;i<curL;i++){
                TreeNode peek = queue.remove();
                temp.add(peek.val);
                if (peek.left!=null){
                    queue.add(peek.left);
                }
                if (peek.right!=null){
                    queue.add(peek.right);
                }                
            }
            res.add(0,temp);
        }
        return res;
    }
}

results matching ""

    No results matching ""