当前位置:网站首页>LeetCode #101. Symmetric Binary Tree
LeetCode #101. Symmetric Binary Tree
2022-08-09 12:32:00 【Zhang Chuming ZCM】
Method 1: Recursion
Symmetry means that the left and right word counts of the entire binary tree are also symmetrical.
Then compare the left node of the left subtree with the right node of the right subtree, and the right node of the left subtree with the left node of the right subtree. If each node is equal in this structure, then the binary treesymmetry.As long as there is one inequality in the middle, it must be asymmetrical.
Use the recursive method to move the pointers of the left and right subtrees synchronously. When the left subtree moves to the left, the right subtree moves to the right, and vice versa.Check whether the values of the two pointers are equal each time, if they are all equal, return True, and return False as long as they are not equal.
class Solution:def isSymmetric(self, root: Optional[TreeNode]) -> bool:return self.compare(root.left, root.right)def compare(self, p: Optional[TreeNode], q:Optional[TreeNode]) -> bool:if p == None and q == None:return Trueif p == None or q == None:return Falseif p.val != q.val:return Falseelse:return self.compare(p.left, q.right) and self.compare(p.right, q.left)
Complexity Analysis
Time complexity:
Space Complexity:
Complete test code
from typing import Optionalclass TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightclass Solution:def isSymmetric(self, root: Optional[TreeNode]) -> bool:return self.compare(root.left, root.right)def compare(self, p: Optional[TreeNode], q:Optional[TreeNode]) -> bool:if p == None and q == None:return Trueif p == None or q == None:return Falseif p.val != q.val:return Falseelse:return self.compare(p.left, q.right) and self.compare(p.right, q.left)class main:a = Solution()node1 = TreeNode(1)node2 = TreeNode(2)node3 = TreeNode(2)node4 = TreeNode(3)node5 = TreeNode(4)node6 = TreeNode(4)node7 = TreeNode(3)node1.left = node2node1.right = node3node2.left = node4node2.right = node5node3.left = node6node3.right = node7b = a.isSymmetric(node1)print(b)if __name__ == '__main__':main()
Method 2: Iteration
First set up a list and enqueue the binary tree root node root twice.Each time two nodes are extracted from the queue for comparison, if it is empty, it will be skipped, and if it is different, False will be returned.Then the nodes of the next layer are added for comparison.When adding a new layer of nodes, pay attention to enqueue the left and right child nodes of the two nodes in reverse order.
This is repeated, as long as there is an inequality in the middle, it returns False, and when the loop traversal is complete, it returns True.
class Solution:def isSymmetric(self, root: Optional[TreeNode]) -> bool:queue = [root, root]while queue:p, q = queue.pop(), queue.pop()if not p and not q:continueif not p or not q:return Falseif p.val != q.val:return Falsequeue.append(p.left)queue.append(q.right)queue.append(p.right)queue.append(q.left)return True
Complexity Analysis
Time complexity:
Space Complexity:
边栏推荐
- PM2之配置文件
- 我们真的需要DApp吗?App真的不能满足我们的幻想吗?
- 元宇宙:下一代互联网启程(附元宇宙深度报告PDF)
- 2022 全球 AI 模型周报
- 专业人士使用的 11 种渗透测试工具
- [现代控制理论]3_Phase_portrait 相图 相轨迹
- How should the acceptance criteria for R&D requirements be written?| Agile Practices
- 【Adobe Premiere Pro 2020】pr2020安装和基本操作【PR安装、新建项目流程、导入及管理素材项目文件、添加标记、创建出入点剪辑视频、快速剪接及自动音乐卡点的方法
- Fapi_StatusType Fapi_issueProgrammingCommand使用注意事项
- TIC2000调用API函数Flash擦除片上FLASH失败
猜你喜欢
京东架构师呕心整理:jvm与性能调优有哪些核心技术知识点
ThreadLocal的简单理解
Byte Qiu Zhao confused me on both sides, and asked me under what circumstances would the SYN message be discarded?
Shell正则表达式,三剑客之grep命令
【面试高频题】可逐步优化的链表高频题
VS Code有趣插件
GRPC整体学习
How should the acceptance criteria for R&D requirements be written?| Agile Practices
Win10调整磁盘存储空间详解
抗积分饱和 PID代码实现,matlab仿真实现
随机推荐
虚拟机安装出现的问题汇总
Oracle Database Architecture
matlab simulink的scope 示波器光标如何移动记录
win10右键文件,一直转圈
[现代控制理论]4_PhasePortrait爱情故事动态系统分析
Recommend a free 50-hour AI computing platform
香港服务器如何进行加密?
【重要】C语言进阶 -- 自定义类型:结构体、枚举、联合
【面试高频题】可逐步优化的链表高频题
Shell之常用小工具(sort、uniq、tr、cut)
Web console control edit box
2022 Niu Ke Duo School (6) M. Z-Game on grid
redis的线程模型
阿里高工带来的20022最新面试总结太香了
太卷了... 腾讯一面被问到内存满了,会发生什么?
2022牛客多校(六)M. Z-Game on grid
WPF 实现带蒙版的 MessageBox 消息提示框
ACM longest non-descent subsequence problem
【无标题】
Django cannot link mysql database