算法打卡第六天

110 阅读3分钟

问题

  1. 面试题32 - I. 从上到下打印二叉树
  2. 剑指 Offer 32 - II. 从上到下打印二叉树 II
  3. 剑指 Offer 32 - III. 从上到下打印二叉树 III

可能不是很完善,请大佬谅解,有好的解法请评论

面试题32 - I. 从上到下打印二叉树

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

题意理解: 按层打印二叉树 方法一:

  1. 采用广度优先算法,声明两个数组,一个用来保存结果,一个用来保存当前层的节点
  2. 遍历保存当前层节点的数组,如果有值就继续,没有则退出 方法二: 利用队列的特性,先进先出原则,遍历次队列,有子节点就入队,没有就不处理 知道队列为空,结束循环。

测试用例: 输入:

3

/
9 20

/  \

15 7 输出:[3, 9, 20, 15, 7]

// 广度优先
if (!root) {
    return [];
}
let output = [];
let currentRow = [root];
while (currentRow.length) {
    let row = [];
    for (let i = 0; i < currentRow.length; i++) {
        output.push(currentRow[i].val)
        currentRow[i].left && row.push(currentRow[i].left)
        currentRow[i].right && row.push(currentRow[i].right)
    }
    currentRow = row;
}
return output;

// 队列
if (!root) {
    return []
}
let out = [];
let tree = [root];
while (tree.length) {
    const current = tree.shift();
    out.push(current.val)
    current.left && tree.push(current.left)
    current.right && tree.push(current.right)
}
return out;

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

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

题意理解: 按层打印二叉树,即输出是个二位数组

  1. 采用广度优先算法,声明两个数组,一个用来保存结果,一个用来保存当前层的节点
  2. 遍历一层保存一层,如有有左子树就保存左子树,如果有右子树就保存右子树。将这些保存到一个数据数组中,只需判断此数组无数据就结束循环
  3. 保存数组二层数据是需要一个零时变量保存一下

测试用例: 给定的二叉树

3

/
9 20

/  \

15 7 输出: [[3], [9, 20], [15, 7]]

if (!root) {
    return [];
}
let output = [];
let currentRow = [root];
while (currentRow.length) {
    let row = [];
    let value = [];
    for (let i = 0; i < currentRow.length; i++) {
        value.push(currentRow[i].val)
        currentRow[i].left && row.push(currentRow[i].left)
        currentRow[i].right && row.push(currentRow[i].right)
    }
    currentRow = row;
    output.push(value)
}
return output;

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

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

题意理解: 按层打印二叉树,即输出是个二位数组

  1. 采用广度优先算法,声明两个数组,一个用来保存结果,一个用来保存当前层的节点
  2. 遍历一层保存一层,如有有左子树就保存左子树,如果有右子树就保存右子树。将这些保存到一个数据数组中,只需判断此数组无数据就结束循环
  3. 保存数组二层数据是需要一个零时变量保存一下,并且保存时需要一次是正序排列一次是反序排列

测试用例: 给定的二叉树

3

/
9 20

/  \

15 7 输出: [[3], [20, 9], [15, 7]]

if (!root) {
    return [];
}
let output = [];
let currentRow = [root];
let isPositive = true;
while (currentRow.length) {
    const row = [];
    const value = [];
    for (let i = 0; i < currentRow.length; i++) {
        isPositive ? value.push(currentRow[i].val) : value.unshift(currentRow[i].val)
        currentRow[i].left && row.push(currentRow[i].left)
        currentRow[i].right && row.push(currentRow[i].right)
    }
    isPositive = !isPositive;
    currentRow = row;
    output.push(value)
}
return output;