zoukankan      html  css  js  c++  java
  • 之字形打印二叉树

    题目:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类

    更好理解的思路:在按层遍历二叉树(上一题)的基础上 加个奇数偶数的判断就行

    import java.util.*;
    public class Solution {
        public ArrayList<ArrayList<Integer> > Print(TreeNode r) {
            ArrayList<ArrayList<Integer>> res = new ArrayList<>();
            if (r == null) return res;
            ArrayList<Integer> l = new ArrayList<>();
            LinkedList<TreeNode> q = new LinkedList<>();
            int start = 0;
            q.addLast(r);
            int end = q.size();
            boolean isJi = true;
            while(!q.isEmpty()){
                TreeNode t = q.removeFirst();
                l.add(t.val);
                start++;
                if(t.left!=null) q.addLast(t.left);
                if(t.right!=null) q.addLast(t.right);
                if(start == end){
                    start = 0;
                    end = q.size();
                    if(isJi){
                        res.add(new ArrayList<>(l));
                    }else{
                        Collections.reverse(l);
                        res.add(new ArrayList<>(l));
                    }
                     isJi = !isJi;
                    l.clear();
                }
            }
            return res;
        }
    
    }

    思路:leetcode上的最优解,思路就是dfs,而不是一层一层遍历,层数是偶数(0,2,4。。。)时,顺序添加相应的节点的数字,而奇数层时(1,3,5。。),每次插到arraylist最开头,也就是index为0的位置,ArrayList会扩充最前面的长度,就实现了转置

    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
            ArrayList<ArrayList<Integer>> res=new ArrayList<>();
            travel(pRoot,res,0);
            return res;
        }
        private void travel(TreeNode curr,ArrayList<ArrayList<Integer>> res,int level){
            if(curr==null)return;
            if(res.size()<=level){
                ArrayList<Integer> newLevel=new ArrayList<>();
                res.add(newLevel);
            }
            ArrayList<Integer> collection=res.get(level);
           if(level%2==0) collection.add(curr.val);
            else collection.add(0,curr.val);
            
            travel(curr.left,res,level+1);
            travel(curr.right,res,level+1);
        }
  • 相关阅读:
    Binary Stirling Numbers
    Count the Buildings ( s1 )
    P3375 【模板】KMP字符串匹配
    POJ2151Check the difficulty of problems
    fbx 模型转换 export
    Linux --windows vs
    phyreengine 3.12.0 安装遇到的问题
    A trip through the graphics pipeline 2011 Part 10(翻译)
    服务端 unity
    nsight 使用问题
  • 原文地址:https://www.cnblogs.com/team42/p/6691795.html
Copyright © 2011-2022 走看看