#107 Binary Tree Level Order Traversal II

Description

Given the root of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).

Examples

Example 1:
#107 Binary Tree Level Order Traversal II_第1张图片

Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000

思路

没啥好说的,bfs

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null)
            return new ArrayList<>();
        
        List<List<Integer>> answer = new ArrayList<>();
        List<TreeNode> currLayer = new ArrayList<>();
        currLayer.add(root);
        
        while(currLayer.size() != 0) {
            List<Integer> addAnswer = new ArrayList<>();
            List<TreeNode> nextLayer = new ArrayList<>();
            for (TreeNode node: currLayer) {
                addAnswer.add(node.val);
                if (node.left != null)
                    nextLayer.add(node.left);
                if (node.right != null)
                    nextLayer.add(node.right);
            }
            answer.add(0, addAnswer);
            currLayer = nextLayer;
        }
        
        return answer;
    }
}

你可能感兴趣的:(leetcode,leetcode,深度优先,算法)