首页 > 其他分享 >leetcode 101 对称二叉树

leetcode 101 对称二叉树

时间:2022-11-16 20:03:39浏览次数:36  
标签:None node2 return li 二叉树 node1 101 leetcode append


题目 给定一个二叉树,检查它是否是镜像对称的。

方法一 递归:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def isSymmetric(self, root: TreeNode) -> bool:

def isMirror(node1, node2):
if node1 is None and node2 is None:
return True
elif node1 is None or node2 is None:
return False
else:
if node1.val != node2.val:
return False
else:
return isMirror(node1.left, node2.right) and isMirror(node1.right, node2.left)

return isMirror(root, root)

使用递归, 速度有点慢

leetcode 101 对称二叉树_对称二叉树

方法二: 迭代

使用列表存储从每个节点交叉遍历的结果,看每相邻的两个是否相同:

def isSymmetric(self, root: TreeNode) -> bool:
li = []
li.append(root)
li.append(root)
while len(li) != 0:
node1 = li.pop()
node2 = li.pop()
if node1 is None and node2 is None:
pass
elif node1 is None or node2 is None:
return False
elif node1.val != node2.val:
return False
else:
li.append(node1.left)
li.append(node2.right)

li.append(node1.right)
li.append(node2.left)
return True

结果如下,更慢了

leetcode 101 对称二叉树_对称二叉树_02

标签:None,node2,return,li,二叉树,node1,101,leetcode,append
From: https://blog.51cto.com/u_13866182/5857534

相关文章

  • LeetCode 110. 平衡二叉树
    给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。classTreeNode:def__in......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:数组中的第K个最大元素
    题目:给定整数数组nums和整数k,请返回数组中第k个最大的元素。请注意,你需要找的是数组排序后的第k个最大的元素,而不是第k个不同的元素。你必须设计并实现时间复杂度......
  • leetcode26. 删除有序数组中的重复项(简单)
    题目:给你一个 升序排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。由于在......
  • LeetCode 题解 1922. 统计好数字的数目
    1922.统计好数字的数目-力扣(Leetcode)题解思路一:快速幂#defineMOD1000000007longlongpower(intn,longlongtimes){if(times==1)returnn;if(ti......
  • LeetCode 题解 46. 全排列
    46.全排列-力扣(Leetcode)题解思路:DFS-注意:力扣测试数据时不会将全局变量重置,要手动重置C代码intptr_line=0;intmark[6];voiddeep_find(intdepth,int*num......
  • [LeetCode] 947. Most Stones Removed with Same Row or Column
    Ona2Dplane,weplace n stonesatsomeintegercoordinatepoints.Eachcoordinatepointmayhaveatmostonestone.Astonecanberemovedifitshareseit......
  • leetcode-560-和为 K 的子数组
    给你一个整数数组nums和一个整数 k,请你统计并返回该数组中和为 k 的连续子数组的个数 。 示例1:输入:nums=[1,1,1],k=2输出:2示例2:输入:nums=[1,2,3],......
  • Leetcode 347 -- 优先队列的坑
    题目描述前k个高频元素坑点在\(C++\)中,可以在\(Class\)中再定义一个\(Class\)对于优先队列的排序,我们要反过来考虑!例如我们使用\(less<int>()\)排序时,我们......
  • [Typescript] 101. Hard - Typed Get
    The get functioninlodash isaquiteconvenienthelperforaccessingnestedvaluesinJavaScript.However,whenwecometoTypeScript,usingfunctionslike......
  • LeetCode75 level3
    LeetCode75level3第1天191.位1的个数136.只出现一次的数字90.子集II第2天5.最长回文子串49.字母异位词分组28.找出字......