当前位置:网站首页>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:
边栏推荐
- Open3D point cloud average point spacing evaluation
- BISS绝对值编码器_TI方案_线路延迟补偿
- Byte Qiu Zhao confused me on both sides, and asked me under what circumstances would the SYN message be discarded?
- TIC2000调用API函数Flash擦除片上FLASH失败
- C# Get system installed .NET version
- PAT1004
- 【Adobe Premiere Pro 2020】pr2020安装和基本操作【PR安装、新建项目流程、导入及管理素材项目文件、添加标记、创建出入点剪辑视频、快速剪接及自动音乐卡点的方法
- 索引index
- Shell正则表达式,三剑客之grep命令
- 京东架构师呕心整理:jvm与性能调优有哪些核心技术知识点
猜你喜欢
redis库没法引入
The redis library cannot be imported
【面试高频题】可逐步优化的链表高频题
【Data augmentation in NLP】——1
【小程序】低代码+小游戏=小游戏可视化开发
信息系统项目管理师必背核心考点(六十三)项目组合管理的主要过程&DIPP分析
proto3-2 syntax
JD.com architects tidy up: what are the core technical knowledge points of jvm and performance tuning
ThreadLocal的简单理解
阿里高工带来的20022最新面试总结太香了
随机推荐
防止数据冒用的方法
redis缓存如何保证数据一致性
[现代控制理论]6_稳定性_李雅普诺夫_Lyapunov
C2000在线升级主程序下载kernel完成后跳转到kernel运行的过程记录
electron 应用开发优秀实践
网页控制台控制编辑框
Django 无法链接mysql数据库
PAT1014 未解决
The use of gdb tui
proto3-2语法
TIC2000系列处理器在线升级
JD.com architects tidy up: what are the core technical knowledge points of jvm and performance tuning
标准C语言学习总结14
学长告诉我,大厂MySQL都是通过SSH连接的
虚拟机安装出现的问题汇总
web课程设计
LeetCode #101. 对称二叉树
抗积分饱和 PID代码实现,matlab仿真实现
VS Code有趣插件
Two ways to enter the Oracle database