前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Leetcode】107. 二叉树的层次遍历 II

【Leetcode】107. 二叉树的层次遍历 II

作者头像
Leetcode名企之路
发布2019-03-19 16:01:50
4160
发布2019-03-19 16:01:50
举报
文章被收录于专栏:Leetcode名企之路Leetcode名企之路

题目

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

例如: 给定二叉树 [3,9,20,null,null,15,7],

代码语言:javascript
复制
    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层次遍历为:

代码语言:javascript
复制
[
  [15,7],
  [9,20],
  [3]
]

题解

利用层次遍历,层次遍历的时候进入下一层的时候记录一下当前队列中有几个元素。

代码语言:javascript
复制
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new LinkedList<>();
        if (root == null) {
            return res;
        }

        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> levelVal = new LinkedList<>();
            while (size > 0) {
                TreeNode current = queue.poll();
                if (current.left != null) {
                    queue.add(current.left);
                }

                if (current.right != null) {
                    queue.add(current.right);
                }
                levelVal.add(current.val);
                size--;
            }
            res.add(0, levelVal);
        }

        return res;
    }
}

用递归去做。 用递归去做的关键在于需要把层数也带上。

代码语言:javascript
复制
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        helper(root, res, 0);
        return res;
    }

    public void helper(TreeNode root, List<List<Integer>> res, int depth) {
        if (root == null) {
            return;
        }

        if (depth == res.size()) {
            res.add(0, new LinkedList<>());
        }

        List<Integer> current = res.get(res.size() - depth - 1);
        helper(root.left, res, depth + 1);
        helper(root.right, res, depth + 1);
        current.add(root.val);
    }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-03-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Leetcode名企之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档