数据结构与算法-二叉树-层次遍历II

二叉树的层次遍历II

给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

示例 1:

数据结构与算法-二叉树-层次遍历II_第1张图片

输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]

思路:这道题与上一道题是一样的,只不过在列表中的顺序是相反的。刚开始的思路想着把List反转,或者是先放到栈里面,然后在遍历出来。看了答案后又更简单的方法,就是用LinkedList,每次遍历完一层的时候,直接用LinkedList.add(0,List) 插入,这样可以在将List插入到头位置。

解题:

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

你可能感兴趣的:(数据结构与算法,算法,java)