【层次遍历】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;
    }   
}
相关推荐
豆豆的java之旅9 分钟前
软考中级软件设计师 数据结构详细知识点(含真题+练习题,可直接复习)
java·开发语言·数据结构
北顾笙98014 分钟前
day07-数据结构力扣
数据结构
hanlin0318 分钟前
刷题笔记:力扣第43、67题(字符串计算)
笔记·算法·leetcode
yang_B62119 分钟前
最小二乘法 拟合平面
算法·平面·最小二乘法
放下华子我只抽RuiKe527 分钟前
深度学习全景指南:硬核实战版
人工智能·深度学习·神经网络·算法·机器学习·自然语言处理·数据挖掘
吴秋霖1 小时前
【某音电商】protobuf聊天协议逆向
python·算法·protobuf
m0_587958951 小时前
C++中的命令模式变体
开发语言·c++·算法
似水এ᭄往昔2 小时前
【数据结构】--链表OJ
数据结构·算法·链表
剑心诀2 小时前
02 数据结构(C) | 线性表——顺序表的基本操作
c语言·开发语言·数据结构
2501_924952692 小时前
代码生成器优化策略
开发语言·c++·算法