zoukankan      html  css  js  c++  java
  • LeetCode:二叉树的层次遍历||【107】

    LeetCode:二叉树的层次遍历||【107】

    题目描述

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

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

        3
       / 
      9  20
        /  
       15   7
    

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

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

    题目分析

      依然是二叉树的层次遍历,采取BFS算法,最后的逆序只是一个小插曲而已。

    Java题解

    /**
     * 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) {
                    List<List<Integer>> ans = new ArrayList<>();
            List<Integer> line = new ArrayList<>();
     
            if(root == null)
                return ans;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
     
            line.add(root.val);
            ans.add(line);
            line =  new ArrayList<>();
     
            int size = queue.size();
            int flag = 1;
            while(!queue.isEmpty())
            {
                TreeNode tmp  = queue.poll();
                if(tmp.left!=null)
                {
                    queue.add(tmp.left);
                    line.add(tmp.left.val);
                }
                if(tmp.right!=null)
                {
                    queue.add(tmp.right);
                    line.add(tmp.right.val);
                }
     
                size--;
                if(size==0&&line.size()>0)
                {
                    size=queue.size();
                    ans.add(line);
                    line = new ArrayList<>();
                }
            }
            Collections.reverse(ans);
            return ans;
        }
    }
    

      

  • 相关阅读:
    免费的mail server
    opensuse 11.2/11.3安装vmware server 1.0.10笔记
    cisco IOS 免费下载的地方
    自动打开最快镜像站
    [ZT]MSSQL清空或者压缩日志的方法
    Cisco路由器的安全配置方案[zt]
    CISCO2821系列路由器恢复密码
    RTorrent User Guide
    Asp.Net发送邮件详解
    C#在线生成网页缩略图
  • 原文地址:https://www.cnblogs.com/MrSaver/p/9809054.html
Copyright © 2011-2022 走看看