107. Binary Tree Level Order Traversal II

来源:互联网 发布:知乎b站三国演义 编辑:程序博客网 时间:2024/06/10 23:46

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,null,null,15,7],

    3   / \  9  20    /  \   15   7

return its bottom-up level order traversal as:

[  [15,7],  [9,20],  [3]]
BFS遍历,linkedlist存储,从上到下把每层元素存到0的位置。代码如下:

/** * 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) {        List<List<Integer>> res = new LinkedList<List<Integer>>();        Queue<TreeNode> queue = new LinkedList<TreeNode>();        if (root == null) return res;        queue.offer(root);        while(!queue.isEmpty()) {            int nodecount = queue.size();            List<Integer> subList= new ArrayList<Integer>();            for (int i = 0; i < nodecount; i++) {                if(queue.peek().left != null) queue.offer(queue.peek().left);                if(queue.peek().right != null) queue.offer(queue.peek().right);                subList.add(queue.poll().val);            }            res.add(0, subList);        }        return res;    }}

0 0