【亡羊补牢】挑战数据结构与算法 第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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月02日 23时43分38秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【Scala 教程】Scala 集合类型
2019-04-29
【Scala 教程】Scala 类、对象和特征
2019-04-29
【Scala 教程】Scala 模式匹配与异常处理
2019-04-29
Linux基础学习--VIM编辑器
2019-04-29
Linux基础学习--别名和重定向
2019-04-29
VMware中手动离线更新Nessus
2019-04-29
Nessus虚拟机不能ping通本机
2019-04-29
kali Linux安装vmtools及重启之后自检1分30秒解决方法
2019-04-29
密码学与网络安全
2019-04-29
常见的wireshark抓包方式
2019-04-29
第三方运维工具连接kali
2019-04-29
分布式系统中的Gossip协议与比特币中的区块链技术
2019-04-29
imageio, imread pilmode
2019-04-29
六种GAN评估指标的综合评估
2019-04-29
JAVA 并发问题
2019-04-29
JAVA 静态代理模式
2019-04-29
JAVA Lambda表达式
2019-04-29
JAVA 线程停止
2019-04-29
JAVA 线程休眠 sleep 与 线程礼让 yield
2019-04-29