LeetCode-103. 二叉树的锯齿形层序遍历-Java-medium

题目链接

法一
    /**
     * 法一
     *
     * @param root
     * @return
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) {
            return ans;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            List<Integer> level = new LinkedList<>();
            int levelSize = q.size();
            while (levelSize > 0) {
                TreeNode now = q.poll();
                if (ans.size() % 2 == 0) { // 根据当前所在层数判断是否需要逆序
                    level.add(now.val);
                } else {
                    level.add(0, now.val); // 头插
                }
                if (now.left != null) {
                    q.offer(now.left);
                }
                if (now.right != null) {
                    q.offer(now.right);
                }
                levelSize--;
            }
            ans.add(level);
        }
        return ans;
    }
法二(快)
    /**
     * 法二(快)
     *
     * @param root
     * @return
     */
    public List<List<Integer>> zigzagLevelOrder_2(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) {
            return ans;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        boolean flag = true; // 标记是否需要逆序,true代表不需要,false代表需要
        while (!q.isEmpty()) {
            int levelSize = q.size();
            Integer[] level = new Integer[levelSize];
            while (levelSize > 0) {
                TreeNode now = q.poll();
                level[flag ? level.length - levelSize : levelSize - 1] = now.val;
                if (now.left != null) {
                    q.offer(now.left);
                }
                if (now.right != null) {
                    q.offer(now.right);
                }
                levelSize--;
            }
            flag = !flag;
            ans.add(Arrays.asList(level));
        }
        return ans;
    }
本地测试
        /**
         * 103. 二叉树的锯齿形层序遍历
         */
        lay.showTitle(103);
        Solution103 sol103 = new Solution103();
        List<Integer> arr103 = Arrays.asList(3, 9, 20, null, null, 15, 7);
        TreeNode root103 = treeOpt.createTreeByLayerOrder(arr103);
        treeOpt.layerOrder(root103);
        List<List<Integer>> ans103_1 = sol103.zigzagLevelOrder(root103);
        arrayOpt.showIntLists(ans103_1);
        System.out.println();
        List<List<Integer>> ans103_2 = sol103.zigzagLevelOrder_2(root103);
        arrayOpt.showIntLists(ans103_2);

你可能感兴趣的:(#,二叉树,leetcode,java,算法)