当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.107.Binary Tree Level Order Traversal II 二叉树自底向上层次遍历

LeetCode.107.Binary Tree Level Order Traversal II 二叉树自底向上层次遍历

题目描述

107 Binary Tree Level Order Traversal II
https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/

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

相似题目

LeetCode.102.Binary Tree Level Order Traversal 二叉树的层次遍历
LeetCode.107.Binary Tree Level Order Traversal II 二叉树自底向上层次遍历
103 Binary Tree Zigzag Level Order Traversal
https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/


解题过程

public List<List<Integer>> levelOrderBottom(TreeNode root) {
    if (null == root) {
        return Collections.emptyList();
    }

    // 用栈存放 自顶向下 的层次遍历结果,最后出栈即是结果
    Deque<List<Integer>> arrayDeque = new ArrayDeque<>();

    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        // 每层的结点个数
        int size = queue.size();
        List<Integer> levelList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TreeNode treeNode = queue.poll();
            levelList.add(treeNode.val);
            if (null != treeNode.left) {
                queue.offer(treeNode.left);
            }
            if (null != treeNode.right) {
                queue.offer(treeNode.right);
            }
        }
        // 遍历完当前层
        arrayDeque.push(levelList);
    }

    // Deque 流数据就是后进先出的,相当于 Collections.reverse()
    return arrayDeque.stream().collect(Collectors.toList());
}

GitHub代码

algorithms/leetcode/leetcode/_107_BinaryTreeLevelOrderTraversal2.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_107_BinaryTreeLevelOrderTraversal2.java


上一篇 LeetCode.108.Convert Sorted Array to Binary Search Tree 升序数组转BST

下一篇 LeetCode.102.Binary Tree Level Order Traversal 二叉树的层次遍历

阅读
评论
303
阅读预计1分钟
创建日期 2020-01-21
修改日期 2020-01-21
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论