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

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

解题思路

  • 改造二叉树的层次遍历算法
  • 设置一个控制变量进行控制方向
java 复制代码
/**
 * 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>> result = new ArrayList<>();
            if(root == null){
                return result;
            }
            Queue<TreeNode> q =  new LinkedList<>();
            q.offer(root);// 入队
            boolean flag = true;// 从左向右
            while(!q.isEmpty()){
                int size = q.size();
                LinkedList<Integer> list = new LinkedList<>();

                // 遍历当前层
                for(int i = 0; i < size; i++){
                    // 出队
                    TreeNode cur = q.poll();
                    // list.add(cur.val);

                    if(flag == true){
                        list.addLast(cur.val);
                    }else{
                        list.addFirst(cur.val);
                    }
                        if(cur.left != null){
                            q.offer(cur.left);
                        }
                                  if(cur.right != null){
                            q.offer(cur.right);
                        }

                }

                result.add(list);

                flag = !flag;

            }


            return result;
    }   
}
相关推荐
夏末秋也凉39 分钟前
力扣-回溯-491 非递减子序列
数据结构·算法·leetcode
penguin_bark41 分钟前
三、动规_子数组系列
算法·leetcode
kyle~1 小时前
thread---基本使用和常见错误
开发语言·c++·算法
曲奇是块小饼干_1 小时前
leetcode刷题记录(一百零八)——322. 零钱兑换
java·算法·leetcode·职场和发展
小wanga2 小时前
【leetcode】滑动窗口
算法·leetcode·职场和发展
少年芒2 小时前
Leetcode 490 迷宫
android·算法·leetcode
BingLin-Liu2 小时前
蓝桥杯备考:搜索算法之枚举子集
算法·蓝桥杯·深度优先
码农诗人2 小时前
调用openssl实现加解密算法
算法·openssl·ecdh算法
老菜鸡mou2 小时前
[OD E 100] 生成哈夫曼树
数据结构·c++
IT猿手2 小时前
2025最新智能优化算法:鲸鱼迁徙算法(Whale Migration Algorithm,WMA)求解23个经典函数测试集,MATLAB
android·数据库·人工智能·算法·机器学习·matlab·无人机