• Binary Tree Level Order Traversal II(层序遍历2)


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

    这里要求层序遍历,而且结果是从下往上,不是从上往下。

    思路:1.可以继续从上往下添加到list中,最后反过来放到另一个list中返回

        2:使用list中的add(index,element)方法,该方法是往index位置插入元素,该位置上原来的元素以及后面所有元素往后移,这里只需往0处一直插入就行,就会自动往后移。因为插入会移动后面所有元素,所以此时适合linkedList。

    代码1:

    class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> tem=new ArrayList<List<Integer>>();
            if(root==null) return tem;
            Queue<TreeNode> q=new LinkedList<>();
            List<Integer> list=new ArrayList<>();
            q.add(root);
            while(!q.isEmpty()){
                int size=q.size();
                for(int i=0;i<size;i++){
                    TreeNode node=q.poll();
                    list.add(node.val);
                    if(node.left!=null) q.add(node.left);
                    if(node.right!=null) q.add(node.right);
                }
                tem.add(list);
         
                list=new ArrayList();
            }
            
           List<List<Integer>> result=new ArrayList<List<Integer>>();
            for(int i=tem.size()-1;i>=0;i--)
                result.add(tem.get(i));
            return result;
            
        }
    }

    代码2:

      public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> tem=new LinkedList<List<Integer>>();
            if(root==null) return tem;
            Queue<TreeNode> q=new LinkedList<>();
            List<Integer> list=new ArrayList<>();
            q.add(root);
            while(!q.isEmpty()){
                int size=q.size();
                for(int i=0;i<size;i++){
                    TreeNode node=q.poll();
                    list.add(node.val);
                    if(node.left!=null) q.add(node.left);
                    if(node.right!=null) q.add(node.right);
                }
                tem.add(0,list);
              
                list=new ArrayList();
            }
           
            return tem;
            
        }
    
    
  • 相关阅读:
    iuplua test failure
    lua C++ wrapper
    lua
    Redux系列01:从一个简单例子了解action、store、reducer
    Meteor入门介绍
    Express入门介绍vs实例讲解
    React半科普文
    Express模版引擎hbs备忘
    Gulp:插件编写入门
    gulp.src()内部实现探究
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8074661.html
Copyright © 2020-2023  润新知