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);
        }
  • 相关阅读:
    记录Log4Net的使用
    利用Ihttpmodel实现网站缓存,解决Server.Transfer 直接输出HTML源代码的问题
    ASP.NET利用byte检测上传图片安全
    通过cmd命令安装、卸载、启动和停止Windows Service(InstallUtil.exe)-大壮他哥
    winform利用代码将控件置于顶端底端
    查询
    字符数组实例化
    三维数组
    填充和批量替换
    遍历二维数组
  • 原文地址:https://www.cnblogs.com/team42/p/6691795.html
Copyright © 2011-2022 走看看