【层次遍历】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;
    }   
}
相关推荐
shehuiyuelaiyuehao25 分钟前
算法44,模拟算法,数青蛙
算法·哈希算法·散列表
hanlin0338 分钟前
刷题笔记:力扣第287题-寻找重复数
笔记·算法·leetcode
kevin_kang1 小时前
第02章 对话时间线与延迟分析
算法
科学实验家1 小时前
最小生成树:Prim,kruskal
数据结构·c++·算法
学习智者1 小时前
《玄》IDE v3.6.3重磅发布:全功能修复与性能飞跃
开发语言·c++·ide·算法·中文语言 玄
Jasmine_llq1 小时前
《P10263 [GESP202403 八级] 公倍数问题》
算法·数论·快速 io 优化·埃氏筛(倍数枚举)·线性遍历求和
橘子汽水1681 小时前
Leetcode 322 279 零钱兑换,完全平方数
算法·leetcode
kevin_kang1 小时前
第01章 VoiceAgent 的总体架构与完整流程
算法
Lintongzg1 小时前
KV-Cache 的显存账本:长上下文、并发与量化剪枝的取舍
算法·机器学习·剪枝
小孩玩什么1 小时前
深入理解字符串匹配算法:BF算法,KMP算法
java·c语言·开发语言·数据结构·c++·算法