【层次遍历】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;
    }   
}
相关推荐
Languorous.20 分钟前
C++数据结构高阶|B+树深度解析:从底层原理到数据库应用,面试高频考点全覆盖
数据结构·b树·面试
洛水水20 分钟前
【力扣100题】39.二叉树的最近公共祖先
算法·leetcode·职场和发展
无敌昊哥战神30 分钟前
【LeetCode 134】加油站:图解指针跳跃与 O(N) 极简贪心,避开 Python 隐藏坑!
c语言·python·算法·leetcode
人道领域34 分钟前
【LeetCode刷题日记】222.极速计算完全二叉树节点数:O(log²n)算法揭秘
java·数据结构·算法·leetcode·深度优先
目黑live +wacyltd39 分钟前
算法备案的实操指南(含截图示例)
人工智能·算法·llm·大模型备案·算法备案
小糯米60140 分钟前
C语言 指针4
c语言·数据结构·算法
洛水水44 分钟前
【力扣100题】36.二叉树展开为链表
算法·leetcode·链表
lwf0061641 小时前
PNN (Product-based Neural Network) 学习日记
算法·机器学习
ZPC82101 小时前
YOLO-3D + 双目相机 (RGB + 深度 + 点云) → 3D 位置 + 抓取姿态
人工智能·算法·计算机视觉·机器人
ZPC82101 小时前
YOLOv8-3D(3D 目标检测 + 6D 抓取姿态)
算法·机器人