107-Binary Tree Level Order Traversal II

kevin聰發表於2018-05-02

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

問題描述

給定二叉樹, 返回其由底向上的層級遍歷的值序列


問題分析

只需要將層級遍歷後的值序列通過集合框架的reverse逆序即可

需要注意利用depth


解法

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

        dfs(root, 0, res);
        Collections.reverse(res);

        return res;
    }

    public void dfs(TreeNode root, int depth, List<List<Integer>> res) {
        if(root == null)   return;
        if(depth == res.size())    res.add(new ArrayList());

        res.get(depth).add(root.val);
        dfs(root.left, depth + 1, res);
        dfs(root.right, depth + 1, res);
    }
}

相關文章