【层次遍历】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;
    }   
}
相关推荐
一叶知秋061 小时前
数据结构-什么是队列?
数据结构·队列
Jasmine_llq2 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计
小棠师姐2 小时前
支持向量机(SVM)入门:超平面与核函数的通俗解释
算法·python机器学习·支持向量机svm·超平面可视化·核函数应用
zhongvv2 小时前
对单片机C语言指针的一些理解
c语言·数据结构·单片机·指针·汇编语言
im_AMBER2 小时前
Leetcode 102 反转链表
数据结构·c++·学习·算法·leetcode·链表
今儿敲了吗2 小时前
01|多项式输出
c++·笔记·算法
Xの哲學3 小时前
深入剖析Linux文件系统数据结构实现机制
linux·运维·网络·数据结构·算法
AlenTech3 小时前
200. 岛屿数量 - 力扣(LeetCode)
算法·leetcode·职场和发展
C雨后彩虹3 小时前
竖直四子棋
java·数据结构·算法·华为·面试
不如自挂东南吱4 小时前
空间相关性 和 怎么捕捉空间相关性
人工智能·深度学习·算法·机器学习·时序数据库