【层次遍历】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;
    }   
}
相关推荐
j_xxx404_5 分钟前
C++算法:前缀和与哈希表实战
数据结构·算法·leetcode
我能坚持多久6 分钟前
【初阶数据结构07】——栈与队列的代码实现与解析
数据结构
We་ct30 分钟前
LeetCode 22. 括号生成:DFS回溯解法详解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
mit6.82438 分钟前
tabbi风波|开源协议
算法
是梦终空11639 分钟前
C++中的职责链模式变体
开发语言·c++·算法
仰泳的熊猫44 分钟前
题目2270:蓝桥杯2016年第七届真题-四平方和
c++·算法·蓝桥杯
CoovallyAIHub44 分钟前
CVPR 2026 | VisualAD:去掉文本编码器,纯视觉也能做零样本异常检测
算法·架构·github
CoovallyAIHub1 小时前
东南大学提出 AutoIAD:多 Agent 驱动的工业异常检测自动化框架
算法·架构·github
ccLianLian1 小时前
算法·字符串
算法·哈希算法