zoukankan      html  css  js  c++  java
  • leetcode刷题笔记一百零三题 二叉树的锯齿层次遍历

    leetcode刷题笔记一百零三题 二叉树的锯齿层次遍历

    源地址:103. 二叉树的锯齿形层次遍历

    问题描述:

    给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

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

    3

    /
    9 20
    /
    15 7
    返回锯齿形层次遍历如下:

    [
    [3],
    [20,9],
    [15,7]
    ]

    /**
    本题与102题基本一致,可分为迭代与递归的方法,基本思路一致,需要设置一个Order变量指示当前插入方向
    迭代方法:可以使用双端对列,这里我使用的还是queue,只是根据当order_left为false时,插入floorRes.reverse
    递归方法:DFS思想基本一致,就是根据order值和level%2的值,选择插入floorRes头部还是尾部
    */
    /**
     * Definition for a binary tree node.
     * class TreeNode(var _value: Int) {
     *   var value: Int = _value
     *   var left: TreeNode = null
     *   var right: TreeNode = null
     * }
     */
    import scala.collection.mutable
    import util.control.Breaks._
    object Solution {
        def zigzagLevelOrder(root: TreeNode): List[List[Int]] = {
            val queue = new mutable.Queue[TreeNode]()
            var orderLeft = true
            val res = new mutable.ListBuffer[List[Int]]()
            if (root == null) return List()
            queue.enqueue(root)
    
            while (queue.isEmpty == false){
                val queueSize = queue.size
                val floorRes = new mutable.ListBuffer[Int]()
                for(i <- 0 until queueSize){
                    breakable{
                        val tempNode = queue.dequeue
                        if (tempNode == null) break()
                        floorRes += tempNode.value
                        queue.enqueue(tempNode.left)
                        queue.enqueue(tempNode.right)
                    }
                }
                if (orderLeft == true){
                    if(floorRes.size > 0) res += floorRes.toList
                    orderLeft = false   
                }
                else{
                    if(floorRes.size > 0) res += floorRes.reverse.toList
                    orderLeft = true
                }
            }
    
            return res.toList
        }
    }
    
  • 相关阅读:
    2021年年度总结——命运与轮回思考
    Kafka消费端数据过滤方案
    Vue.js知识点汇集
    The POM for is missing .....no dependency information available
    Knife4j 自定义参数解析
    Java List<String> IndexOf(object e)坑
    ES6获取对象数组属性最大最小值
    VM虚拟机(Windows server 2019)分区
    uniapp本地文件的路径
    JS墨卡托坐标与经纬度互转
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13427793.html
Copyright © 2011-2022 走看看