14. 二叉树的层序遍历类型题目【LC103&199】

146 阅读1分钟

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

示例 1:

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

输入:root = [1]
输出:[[1]]
示例 3:

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

核心思路: 就是层序遍历,只是针对性的加了一个标识,确认每层是否反转。

对层序遍历这部分,多说一点,首先确认我们是需要一个queue来承载数据。

关键是怎么按层维度来消费数据。

=> 一次计算完成(包括初始状态),整个queue里只有当前层的元素。

=> 一次计算完成后,queue的长度就是当前层的节点数

=> 只需要按照这个数作为取的次数,从queue中取出当前层的所有节点,

=> 取得过程把下一层的数据塞到queue中。

=> 重新计算queue长度

解:

var zigzagLevelOrder = function (root) {
  if (!root) {
    return [];
  }
  let LTR = true;
  let queue = [root];
  const res = [];
  while (queue.length) {
    let len = queue.length; //控制当前层
    const tempArr = [];
    for (let i = 0; i < len; i++) { // 当前层的元素遍历弹出
    // 一次处理一层
      const node = queue.shift();
      tempArr.push(node.val);
      node.left && queue.push(node.left)
      node.right && queue.push(node.right)
    }
    LTR && res.push(tempArr);
    !LTR && res.push(tempArr.reverse())
    LTR = !LTR
  }
  return res;
};

题目2: 二叉树的右视图【LC199】

给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

解:

var rightSideView = function(root) {
    let res = [];
    if(!root){
        return res
    }
  let queue = [root]
  while(queue.length){
    let len = queue.length;
    for(let i = 0; i < len; i++) {
      const node = queue.shift();
      !i && res.push(node.val);
      node.right && queue.push(node.right)
      node.left && queue.push(node.left)
    }
  }
  return res;
};