题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
         if(pRoot == null) {
            return new ArrayList<>();
        }
         // 方向
        int direction = 0;
        List<TreeNode> head = Arrays.asList(pRoot);
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();

        return executePrint(head, direction, result);

    }

    private ArrayList<ArrayList<Integer>> executePrint(List<TreeNode> head, int direction,
        ArrayList<ArrayList<Integer>> result) {
        ArrayList<Integer> list = new ArrayList<>();
        if (head.size() == 0) {
            return result;
        }

        if(direction == 0) {
		  // 正方向
            for (TreeNode treeNode : head) {
                list.add(treeNode.val);
            }
            List<TreeNode> children = getChildList(head);
            result.add(list);
            executePrint(children, (direction+1)%2, result);
        }else {
		  // 反方向
            List<TreeNode> children = getChildList(head);
		  // head转方向
            Collections.reverse(head);
            for (TreeNode treeNode : head) {
			  // 只是需要转完方向后的值而已
                list.add(treeNode.val);
            }
            result.add(list);
            executePrint(children, (direction+1)%2, result);
        }
        return result;

    }

    private List<TreeNode> getChildList(List<TreeNode> head) {
        if(head.size() == 0)
            return new ArrayList<>();
        List<TreeNode > nodes = new ArrayList<>();
        for (TreeNode treeNode : head) {
            if(treeNode.left!= null) {
                nodes.add(treeNode.left);
            }
            if(treeNode.right!= null) {
                nodes.add(treeNode.right);
            }
        }
        return nodes;
    }
}

全部评论

相关推荐

08-06 15:03
中南大学
真人面试官我唯唯诺诺,AI面试我激情互喷
青春运维少年不会梦到...:好样的,没丢份
点赞 评论 收藏
分享
机械打工仔:不管啥专业,找工作改简历的第一课先把你那排版改了,简历上不要写个人简历四个字,找你要简历的谁不知道这个是简历?而且还占那么多空间,直接把自己名字和基础信息写上面,整体字体大一些。 还有这种经典两页简历一页大空白,导出PDF的时候多了一页几乎全是白的你自己看着不难受吗随手的事为啥不能改掉呢,这是态度问题,你试想一下你是HR你打开简历看到格式都没调整过会是什么感受?你自己都不重视你的简历,HR更不会在意。 然后内容你那个做两年咖啡就别往里写了,简历在精不在多,你在往你的简历里打字的时候就要想好这东西对你要找的工作有没有帮助。自我评价写一行就行了,不如给专业技能单开一栏。核心课程均分90这个真别写了,把你上过的有用的专业课列出来也行。有很多地方废话很多的精炼一下,比如你校内项目第一个写的那些,全然没有重点。 好好修改一下,我看你内容也挺优秀的,别被一个随便做的简历耽误了,我一个同专业的打工人看了都揪心更别说一天看几百份简历的HR
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务