103. 二叉树的锯齿形层序遍历

题目:

思路:

【1】相当于在层次遍历上进行了小修改(如果层数是按0开始的,即碰到奇数层,则将数据倒着放入数组即可)

代码展示:

//时间0 ms 击败 100%
//内存40.2 MB 击败 73.35%
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) return res;

        Queue<TreeNode> que = new LinkedList<>();
        que.add(root);
        int count = que.size();
        TreeNode temp;
        int index = 0;
        while (!que.isEmpty()){
            List<Integer> resList = new ArrayList<>();
            while (count > 0){
                temp = que.poll();
                // 将奇数位置的层次数据进行反转
                if (index % 2 == 1){
                    resList.add(0,temp.val);
                }else {
                    resList.add(temp.val);
                }
                if (temp.left != null) que.add(temp.left);
                if (temp.right != null) que.add(temp.right);
                count--;
            }
            res.add(resList);
            count = que.size();
            index++;
        }

        return res;
    }
}

 

posted @ 2023-06-27 18:47  忧愁的chafry  阅读(2)  评论(0编辑  收藏  举报