当前位置:网站首页>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 TrueComplexity Analysis
Time complexity: 
Space Complexity: 
边栏推荐
猜你喜欢

Information system project managers must memorize the core test sites (63) The main process of project portfolio management & DIPP analysis

太卷了... 腾讯一面被问到内存满了,会发生什么?

IDEA close/open reference prompt Usages
Byte Qiu Zhao confused me on both sides, and asked me under what circumstances would the SYN message be discarded?

LeetCode热题(11.合并两个有序链表)

TIC2000系列处理器在线升级

ThreadLocal的简单理解

读写分离后,性能居然提升100%了呀

《数字经济全景白皮书》银行业智能营销应用专题分析 发布

JD.com architects tidy up: what are the core technical knowledge points of jvm and performance tuning
随机推荐
实验记录:搭建网络过程
Two ways to enter the Oracle database
mysql + redis + flask + flask-sqlalchemy + flask-session 配置及项目打包移植部署
抗积分饱和 PID代码实现,matlab仿真实现
PM2 configuration file
mysql8.0和navicat premium15下载安装
元宇宙:下一代互联网启程(附元宇宙深度报告PDF)
阿里云新增三大高性能计算解决方案,助力生命科学行业快速发展
Semaphore SIGCHLD use, how to make the parent that the child performs over, how to make the distinction between multiple child processes. The end
学长告诉我,大厂MySQL都是通过SSH连接的
web课程设计
_main C:/ti/ccs1011/ccs/tools/compiler/ti-cgt-c2000_20.2.1.LTS/lib/rts2800_fpu32.lib<ar在线升级跳转疑问
Shell正则表达式,三剑客之grep命令
Chinese valentine's day?Programmers don't exist
获取url地址中问号后参数(即使是iframe也可以)
redis内存的淘汰机制
PAT1002
PAT1001
WPF implements a MessageBox message prompt box with a mask
Redis的常用数据结构和底层实现方式