Leetcode 107. Binary Tree Level Order Traversal II

题目链接

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/

题目描述

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]
]

题解

层次遍历,用队列存起来。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new LinkedList<>();
        if (root == null) { return list; }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> subList = new LinkedList<>();
            for (int i = 0; i <size; 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);
            }
            list.add(0, subList);
        }
        return list;
    }
}

posted @ 2018-09-06 10:15  DCREN  阅读(237)  评论(0编辑  收藏  举报