【力扣算法】107-二叉树的层次遍历II

题目

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

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

    3
   / \
  9  20
    /  \
   15   7

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

[
  [15,7],
  [9,20],
  [3]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

无官方题解,可以参考102题的

感想

102题的代码,res改成LinkedList,然后插入list的时候add改成addFirst就行了,这种题目有点无聊了

执行用时 :3 ms, 在所有 Java 提交中击败了68.23%的用户

内存消耗 :36.6 MB, 在所有 Java 提交中击败了38.87%的用户

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> res = new LinkedList<>();//指定使用链表,不然用不了addFirst方法
        if(root==null) return res;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode nextFirst = null;
        TreeNode temp = null;
        List<Integer> list = new LinkedList<>();
        while(!queue.isEmpty()){
            temp = queue.poll();
            if(temp==nextFirst) {
                nextFirst=null;
                res.addFirst(list);//头插法
                list = new LinkedList<>();
            }
            list.add(temp.val);
            if(temp.left!=null){
                queue.add(temp.left);
                if(nextFirst==null) nextFirst = temp.left;
            }
            if(temp.right!=null){
                queue.add(temp.right);
                if(nextFirst==null) nextFirst = temp.right;
            }
        }
        if(list.size()>0) res.addFirst(list);//头插法
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值