【亡羊补牢】挑战数据结构与算法 第46期 LeetCode 101. 对称二叉树(二叉树)
发布日期:2021-06-29 14:34:25 浏览次数:3 分类:技术文章

本文共 1869 字,大约阅读时间需要 6 分钟。

仰望星空的人,不应该被嘲笑

题目描述

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

1   / \  2   2 / \ / \3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

1   / \  2   2   \   \   3    3

进阶:

你可以运用递归和迭代两种方法解决这个问题吗?

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/symmetric-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

dfs,逐层进行比较,即自顶向底找,注意判断几个条件:

  • 如果左右节点都为空,可以
  • 如果左右节点一个为空,不可以
  • 如果左右节点值不相等,不可以
  • 最后递归左右子树镜像

参考 大佬图解

/** * Definition for a binary tree node. * function TreeNode(val) { *     this.val = val; *     this.left = this.right = null; * } *//** * @param {TreeNode} root * @return {boolean} */var isSymmetric = function (root) {
if (!root) return true; let dfs = (left, right) => {
// 如果左右节点都为空,可以 if (left == null && right == null) return true; // 如果左右节点一个为空,不可以 if(left == null || right == null) return false; // 如果左右节点值不相等,不可以 if (left.val !== right.val) return false; // 递归左右子树镜像 return dfs(left.left, right.right) && dfs(left.right, right.left); } return dfs(root.left, root.right);};

解法二

通过队列逐步一层一层来比较,只要出现不对称的情况,直接返回 false

/** * Definition for a binary tree node. * function TreeNode(val) { *     this.val = val; *     this.left = this.right = null; * } *//** * @param {TreeNode} root * @return {boolean} */var isSymmetric = function (root) {
if (!root) return true let queue = [root.left, root.right] while (queue.length) {
let node1 = queue.shift() let node2 = queue.shift() if (!node1 && !node2) continue if (!node1 || !node2 || node1.val !== node2.val) return false queue.push(node1.left) queue.push(node2.right) queue.push(node1.right) queue.push(node2.left) } return true};

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!

,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退

转载地址:https://chocolate.blog.csdn.net/article/details/108795435 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【亡羊补牢】挑战数据结构与算法 第47期 LeetCode 111. 二叉树的最小深度(二叉树)
下一篇:【亡羊补牢】挑战数据结构与算法 第45期 LeetCode 110. 平衡二叉树(二叉树)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月02日 23时43分38秒