【层次遍历】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;
    }   
}
相关推荐
计算机安禾4 分钟前
【算法分析与设计】第44篇:随机化复杂度类:RP、BPP与去随机化猜想
java·数据结构·数据库·算法·机器学习
计算机安禾13 分钟前
【算法分析与设计】第45篇:交互式证明系统与零知识证明
算法·区块链·零知识证明
自进化Agent智能体17 分钟前
Hermes架构全景图:从入口到交付的完整数据流
算法
手写码匠21 分钟前
手写 Prefix Caching:从零构建 LLM 提示词缓存引擎
人工智能·深度学习·算法·aigc
枕星而眠22 分钟前
【数据结构】树与二叉树基础知识点总结
数据结构·c++·后端·算法·运维开发
海梨花23 分钟前
腾讯面试高频算法题
java·算法·面试
珂朵莉MM24 分钟前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--整数线性规划
人工智能·算法
小则又沐风a26 分钟前
今日算法----一篇文章学会背包问题
运维·服务器·算法
2301_7644413338 分钟前
Factorization Machine(FM模型,因子分解机)
python·算法