【层次遍历】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;
    }   
}
相关推荐
思成Codes20 小时前
数据结构: 权值线段树——线段树系列(提供模板)
数据结构·算法
笨手笨脚の20 小时前
链表与LinkedList
java·数据结构·链表·linkedlist
历程里程碑20 小时前
破解三数之和:双指针高效解法
c语言·数据结构·c++·经验分享·算法·leetcode·排序算法
Vect__20 小时前
25.12.27 算法日记——双指针
c++·算法
Swizard20 小时前
数据不够代码凑?用 Albumentations 让你的 AI 模型“看”得更广,训练快 10 倍!
python·算法·ai·训练
AI题库20 小时前
NLTK自然语言处理实战:1.3 NLTK核心数据结构
数据结构·人工智能·自然语言处理
一个专注写代码的程序媛20 小时前
流式读取数据
java·数据结构·算法
Halo_tjn20 小时前
Java Set集合知识点
java·开发语言·数据结构·windows·算法
-Xie-20 小时前
Redis(十六)——底层数据结构(一)
java·数据结构·redis
小园子的小菜20 小时前
深入理解Trie树:敏感词过滤的核心原理与实现思路
算法