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

按之字形顺序打印二叉树

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;
    }
}

全部评论

相关推荐

虽然大家都在劝退读研,说读研以后也是打工,不如本科直接去打工,但随着现在研究生越来越多,很多企业招聘要求就会变成研究生起招,本科投递简历就会被卡,横向比较时也会因为"本科学历比不上研究生学历"被筛掉,而且你没发现劝退读研的基本都是读完研的人吗?而且进体制、国企等,研究生也比本科生升的快,他们拿着研究生文凭劝你一个本科生,可别当真了
炬火初现:肯定是说本科能有好工作或者满意的可以不读研啊,现在本科能找到好工作的那个不优秀,大学四年赛高中,而且还要和学校斗智斗勇,这种时候自然有的选,要是只是觉得一辈子混口饭吃,大概率也考不上研,或者考上又浑浑噩噩三年,也难说。 而且考研所谓的优势说实话是你用差不多四年的时间成本(考一年,读三年)换过来的,而且还未必读完有今年的就业市场,当然不能随便决定读。 再还要看专业,一些稀奇古怪的专业说实话根本没有办法创造出什么价值,也没钱赚(如果有爱好,可以适当降低报酬标准)。现在非92的研究生说实话也没啥太多所谓优势,难说。 所以任何时候都要具体情况具体分析,不能一概而论。 一点点小看法。欢迎大家友善讨论。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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