[路飞]算法:二叉树的锯齿形层序遍历

98 阅读1分钟

103. 二叉树的锯齿形层序遍历

正题

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

示例 1:

image.png

输入: root = [3,9,20,null,null,15,7]
输出: [[3],[20,9],[15,7]]

示例 2:

输入: root = [1]
输出: [[1]]

示例 3:

输入: root = []
输出: []

解析

锯齿形层序遍历实际上就是普通层序遍历的衍生,其不同之处在于每一层的起点是从最左节点开始,还是最右节点开始。实际上只要你了解了层序遍历的原理,那么这个问题就很好解决。

实现普通层序遍历

var zigzagLevelOrder = function(root) {
   const quene = root ? [root] : []
   const res = []
   while(quene.length) {
       const size = quene.length
       const level = []
       for (let index = 0 ; index < size ; index++) {
           const node = quene.shift()
           node.left ? quene.push(node.left) : ''
           node.right ? quene.push(node.right) : ''
           level.push(node.val)
       }
       res.push(level)
   }
   return res
};

这是一个普通的层序遍历, res将会返回每一层都是从左节点开始遍历的层序遍历结果。锯齿形层序遍历要求间隔左右起点,在结果中表现为奇数层保持不变,偶数层结果相反。所以我们只需要利用一个 bool值来交替是否翻转数组即可。

var zigzagLevelOrder = function(root) {
   const quene = root ? [root] : []
   const res = []
   let flag = true // 记录翻转
   while(quene.length) {
       const size = quene.length
       const level = []
       for (let index = 0 ; index < size ; index++) {
           const node = quene.shift()
           node.left ? quene.push(node.left) : ''
           node.right ? quene.push(node.right) : ''
           level.push(node.val)
       }
       res.push( flag ? level : level.reverse()) // 间隔翻转
       flag = !flag // 交替
   }
   return res
};

image.png