zoukankan      html  css  js  c++  java
  • leetcode——107.二叉树的层次遍历II

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
            LinkedList<List<Integer>> res = new LinkedList<>();
            if(root == null){
                return res;
            }
            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            while (!q.isEmpty()){
                LinkedList<Integer> subList = new LinkedList<>();
                int sz = q.size();
                for(int i = 0;i<sz;i++){
                    TreeNode cur = q.poll();
                    subList.offer(cur.val);
                    if(cur.left != null){
                        q.offer(cur.left);
                    }
                    if(cur.right != null){
                        q.offer(cur.right);
                    }
                }
                res.offerFirst(subList);
            }
            return res;
        }

    BFS。

    DFS如下:

    private LinkedList<List<Integer>> ans;
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            ans = new LinkedList<>();
            getOrder(root,1);
            return ans;
        }
    
        private void getOrder(TreeNode root, int level) {
            if(root== null){
                return;
            }
            if(ans.size() < level){
                ans.addFirst(new LinkedList<Integer>());
            }
            List<Integer> subList = ans.get(ans.size() - level);
            subList.add(root.val);
            getOrder(root.left, level+1);
            getOrder(root.right,level+1);
        }

     ——2020.6.30

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    WalkDirFiles
    http://ocpj8.javastudyguide.com/
    打印文件夹中的文件
    apple
    JDBC
    JDBC connection
    Properties-getProperty
    删除目录中指定文件
    spark 之knn算法
    hbase查询基于标准sql规范中间件Phoenix
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13214480.html
Copyright © 2011-2022 走看看