【层次遍历】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;
    }   
}
相关推荐
qq_401700416 分钟前
Linux文件锁解决多进程并发
linux·服务器·算法
长安er27 分钟前
LeetCode 83/237/82 链表删除问题-盒子模型
数据结构·算法·leetcode·链表·力扣
小虎牙0071 小时前
RSA 的核心原理
算法
重生之后端学习1 小时前
56. 合并区间
java·数据结构·后端·算法·leetcode·职场和发展
小猪猪屁1 小时前
顺序表与链表:头插法与尾插法详解
c语言·数据结构·c++
历程里程碑1 小时前
C++ 5:模板初阶
c语言·开发语言·数据结构·c++·算法
leoufung1 小时前
LeetCode 74. Search a 2D Matrix
数据结构·算法·leetcode
Kiri霧1 小时前
Go数据类型介绍
java·算法·golang
Mxsoft6192 小时前
AR远程定位偏差救场!某次现场故障,SLAM算法精准对齐设备模型!
算法·ar