当前位置:网站首页>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: 
边栏推荐
- Recommend a free 50-hour AI computing platform
- 正则表达式(规则,匹配,和实际使用)
- ACM longest non-descent subsequence problem
- 香港服务器如何进行加密?
- 二重指针-char **、int **的作用
- 【Robustness of VQA-1】——2019-EMNLP-Don’t Take the Easy Way Out
- 2022 Niu Ke Duo School (6) M. Z-Game on grid
- 从零开始Blazor Server(9)--修改Layout
- Byte Qiu Zhao confused me on both sides, and asked me under what circumstances would the SYN message be discarded?
- Fapi_StatusType Fapi_issueProgrammingCommand使用注意事项
猜你喜欢

JS封装防抖(代码持续优化)

学长告诉我,大厂MySQL都是通过SSH连接的

【Data augmentation in NLP】——1

F280049库函数API编程、直接寄存器控制编程和混合编程方法

专业人士使用的 11 种渗透测试工具
![[Essence] Analysis of the special case of C language structure: structure pointer / basic data type pointer, pointing to other structures](/img/cc/9e5067c9cedaf1a1797c0509e67f88.png)
[Essence] Analysis of the special case of C language structure: structure pointer / basic data type pointer, pointing to other structures

Semaphore SIGCHLD use, how to make the parent that the child performs over, how to make the distinction between multiple child processes. The end

win10 outlook邮件设置

人体解析(Human Parse)开源数据集整理

在北京参加UI设计培训到底怎么样?
随机推荐
太卷了... 腾讯一面被问到内存满了,会发生什么?
微信小程序支付及退款整体流程
GET请求和POST请求区别
PAT1011
Notepad++安装插件
[现代控制理论]4_PhasePortrait爱情故事动态系统分析
字符串 | 反转字符串 | 双指针法 | leecode刷题笔记
Visual Studio 2017 ASP.NET Framework MVC 项目 MySQL 配置连接
问题来了:4GB物理内存的机器上申请8G内存能成功吗?
web课程设计
学长告诉我,大厂MySQL都是通过SSH连接的
Open3D point cloud average point spacing evaluation
JS封装防抖(代码持续优化)
redis的缓存穿透、缓存雪崩、缓存击穿怎么搞?
ThreadLocal的简单理解
C2000在线升级主程序下载kernel完成后跳转到kernel运行的过程记录
[C language] creation and use of dynamic arrays
Blazor Server (9) from scratch -- modify Layout
GRPC整体学习
Summary of learning stages (knapsack problem)