剑指 Offer 32 - III. 从上到下打印二叉树 III

目录

使用函数实现

使用双端队列实现


请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:

给定二叉树: [3,9,20,null,null,15,7],

复制代码
    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

复制代码
[
  [3],
  [20,9],
  [15,7]
]

提示:

  1. 节点总数 <= 1000

使用函数实现

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<List<Integer>> res=new ArrayList<>();
    public List<List<Integer>> levelOrder(TreeNode root) {
        helper(root,0);
        return res;
    }

    private void helper(TreeNode root,int level){
        if(root==null)
            return;
        if(res.size()==level){
            res.add(new ArrayList<>());
        }
        if(level%2==0){
            res.get(level).add(root.val);

        }else{
            res.get(level).add(0,root.val);
        }
        helper(root.left,level+1);
        helper(root.right,level+1);
    }
}

使用双端队列实现

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        boolean isEven = false;//从1开始,第一行不是偶数
        if(root==null) return new ArrayList<>();
        List<List<Integer>>  ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(true){
            int size = queue.size();
            LinkedList<Integer> item = new LinkedList<>();
            for(int i=0;i<size;i++){
                root = queue.poll();
                if(!isEven) item.addLast(root.val);
                else item.addFirst(root.val);
                
                if(root.left!=null) queue.offer(root.left);
                if(root.right!=null) queue.offer(root.right);
            }
            isEven = !isEven;
            ans.add(item);
            if(queue.isEmpty()) break;
        }
        return ans;
    }
}
相关推荐
lifallen31 分钟前
从Apache Doris 学习 HyperLogLog
java·大数据·数据仓库·算法·apache
智驱力人工智能1 小时前
使用手机检测的智能视觉分析技术与应用 加油站使用手机 玩手机检测
深度学习·算法·目标检测·智能手机·视觉检测·边缘计算
姚瑞南1 小时前
【AI 风向标】四种深度学习算法(CNN、RNN、GAN、RL)的通俗解释
人工智能·深度学习·算法
补三补四2 小时前
SMOTE 算法详解:解决不平衡数据问题的有效工具
人工智能·算法
RTC老炮2 小时前
webrtc弱网-RobustThroughputEstimator源码分析与算法原理
网络·算法·webrtc
努力努力再努力wz2 小时前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python
听风吹等浪起2 小时前
分类算法-逻辑回归
人工智能·算法·机器学习
敲代码的嘎仔2 小时前
JavaWeb零基础学习Day2——JS & Vue
java·开发语言·前端·javascript·数据结构·学习·算法
yacolex3 小时前
3.3_数据结构和算法复习-栈
数据结构·算法
茉莉玫瑰花茶3 小时前
动态规划 - 两个数组的 dp 问题
算法·动态规划