【LeetCode】二叉树的层序遍历——代码随想录算法训练营Day15

1. 二叉树的层序遍历(中等)

题目链接:102. 二叉树的层序遍历

文章讲解:代码随想录

视频讲解:讲透二叉树的层序遍历 | 广度优先搜索 | LeetCode:102.二叉树的层序遍历_哔哩哔哩_bilibili

(1) 迭代方式

思路:借助一个队列保存我们遍历过的每一层中的元素。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    const res = [];
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        const arr = [];
        // 这里一定要使用固定大小 size,不要使用 queue.length,因为 queue.length 是不断变化的
        let size = queue.length;
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            arr.push(node.val);
        }
        res.push(arr);
    }
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

(2) 递归方式

思路:先递归的遍历左子树,将每层节点的值都存入对应层的数组中,再递归的遍历右子树,即可得出层序遍历的结果。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    const res = [];
    const order = function (node, depth) {
        if (!node) {
            return;
        }
        if (res.length === depth) {
            res.push([]);
        }
        res[depth].push(node.val); // 将当前节点的值放入结果数组中对应层的数组
        order(node.left, depth + 1); // 递归的遍历左子树
        order(node.right, depth + 1); // 递归的遍历右子树
    }
    order(root, 0);
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(logn)。

2. 二叉树的层序遍历 II(中等)

题目链接:107. 二叉树的层序遍历 II

思路:和第1题解法相同,区别在于插入到结果数组时从前面插入,即实现了自底向上的层序遍历。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrderBottom = function(root) {
    const res = [];
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        const arr = [];
        let size = queue.length;
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            arr.push(node.val);
        }
        res.unshift(arr);
    }
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

3. 二叉树的右视图(中等)

题目链接:199. 二叉树的右视图

思路:对二叉树进行层序遍历,遍历过程中将每层最后一个节点值插入结果数组中。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function(root) {
    const res = [];
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        let size = queue.length;
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            size === 0 && res.push(node.val); // 将每层最后一个节点值插入结果数组中
        }
    }
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

4. 二叉树的层平均值(简单)

题目链接:637. 二叉树的层平均值

思路:对二叉树进行层序遍历,遍历过程中计算每层的平均值。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var averageOfLevels = function(root) {
    const res = [];
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        let sum = 0;
        const size = queue.length;
        for (let i = 0; i < size; i++) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            sum += node.val;
        }
        res.push(sum / size);
    }
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

5. N 叉树的层序遍历(中等)

题目链接:429. N 叉树的层序遍历

思路:与二叉树的层序遍历类似,借助队列完成 N 叉树的层序遍历。

/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */

/**
 * @param {Node|null} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    const res = [];
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        const arr = [];
        let size = queue.length;
        while (size--) {
            const node = queue.shift();
            node.children.forEach(node => node && queue.push(node));
            arr.push(node.val);
        }
        res.push(arr);
    }
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

6. 在每个树行中找最大值(中等)

题目链接:515. 在每个树行中找最大值

思路:对二叉树进行层序遍历,遍历过程中找出每层的最大值。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var largestValues = function(root) {
    const res = [];
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        let max = -Infinity;
        let size = queue.length;
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            max = node.val > max ? node.val : max;
        }
        res.push(max);
    }
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

7. 填充每个节点的下一个右侧节点指针(中等)

题目链接:116. 填充每个节点的下一个右侧节点指针

(1) 层序遍历

思路:对二叉树进行层序遍历,为每个节点填充右侧节点指针。

/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function(root) {
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        let size = queue.length;
        let pre = null; // 上一个节点
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            if (pre) {
                pre.next = node; // 将上个节点的 next 指向当前节点
            }
            pre = node; // 更新上个节点
        }
    }
    return root;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

(2) 利用“完美二叉树”条件

思路:完美二叉树的所有叶子节点都在同一层,每个父节点都有2个子节点。因此可以一层层建立 next 指针,利用上层的 next 指针建立当前层的 next 指针。有如下2种情况:

  • 若当前节点有子节点,将其左孩子的 next 指针指向其右孩子;
  • 若当前节点有子节点且在同一层有下个节点,将其右孩子的 next 指针指向下个节点的左孩子。
/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function(root) {
    if (!root) {
        return null;
    }
    let leftNode = root;
    while (leftNode.left) {
        let cur = leftNode; // 遍历本层
        while (cur) {
            cur.left.next = cur.right; // 将左孩子的 next 指针指向右孩子
            if (cur.next) {
                cur.right.next = cur.next.left; // 将右孩子的 next 指向下个节点的左孩子
            }
            cur = cur.next; // 继续遍历下个节点
        }
        leftNode = leftNode.left; // 继续遍历下一层
    }
    return root;
};

分析:时间复杂度为 O(n),空间复杂度为 O(1)。

8. 填充每个节点的下一个右侧节点指针 II(中等)

题目链接:117. 填充每个节点的下一个右侧节点指针 II

思路:和第7题的第1种解法一样,虽然这棵树不再是完美二叉树,用第7题的代码还是能解的。

/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function(root) {
    const queue = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length > 0) {
        let size = queue.length;
        let pre = null; // 上一个节点
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            if (pre) {
                pre.next = node; // 将上个节点的 next 指向当前节点
            }
            pre = node; // 更新上个节点
        }
    }
    return root;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

9. 二叉树的最大深度(简单)

题目链接:104. 二叉树的最大深度

(1) 层序遍历

思路:对二叉树进行层序遍历,记录二叉树的层数,二叉树的层数即为二叉树的最大深度。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    const queue = [];
    if (root) {
        queue.push(root);
    }
    let deep = 0;
    while (queue.length > 0) {
        let size = queue.length;
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
        deep++;
    }
    return deep;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

(2) 递归遍历

思路:对二叉树进行递归遍历,二叉树的最大深度即为左子和右子树最大深度大的一方的深度再加1。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (!root) {
        return 0;
    }
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};

分析:时间复杂度为 O(n),空间复杂度为 O(logn)。

10. 二叉树的最小深度

题目链接:111. 二叉树的最小深度

(1) 层序遍历

思路:对二叉树进行层序遍历,记录二叉树的层数,当遇到第1个叶子节点时,这个叶子节点的深度即为二叉树的最小深度。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function(root) {
    const queue = [];
    if (root) {
        queue.push(root);
    }
    let res = 0;
    while (queue.length > 0) {
        res++;
        let size = queue.length;
        while (size--) {
            const node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
            if (!node.left && !node.right) {
                return res; // 当遇到叶子节点时,直接返回当前计算的高度即为二叉树的最小深度
            }
        }
    }
    return res;
};

分析:时间复杂度为 O(n),空间复杂度为 O(n)。

(2) 递归遍历

思路:对二叉树进行递归遍历,二叉树的最小深度即为左子和右子树的最小深度小的一方的深度再加1。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function(root) {
    if (!root) {
        return 0;
    }
    if (root.left && root.right) {
        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
    if (root.left) {
        return minDepth(root.left) + 1;
    }
    if (root.right) {
        return minDepth(root.right) + 1;
    }
    return 1;
};

分析:时间复杂度为 O(n),空间复杂度为 O(logn)。

收获

了解了二叉树的层次遍历,可以使用二叉树的层次遍历和递归遍历来解决一些问题。

  • 25
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
第二十二天的算法训练营主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组,使得子数组的和大于等于给定的目标值。这里可以使用滑动窗口的方法来解决问题。使用两个指针来表示滑动窗口的左边界和右边界,通过移动指针来调整滑动窗口的大小,使得滑动窗口中的元素的和满足题目要求。具体实现的代码如下: ```python def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 right = 0 ans = float('inf') total = 0 while right < len(nums): total += nums[right] while total >= target: ans = min(ans, right - left + 1) total -= nums[left] left += 1 right += 1 return ans if ans != float('inf') else 0 ``` 以上就是第二十二天的算法训练营的内容。通过这些题目的练习,可以提升对双指针和滑动窗口等算法的理解和应用能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晴雪月乔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值