题目描述
链接:https://leetcode-cn.com/problems/symmetric-tree/
解题思路:
递归:与之前相同的树递归类似,不过是要新建一个递归函数,去比较两个结点。
迭代:用队列记录根的左右节点,看是否镜像。然后再把这两个的两个镜像放入队列,再删除最最前面的两个节点。
迭代结束的标志是1.出现不镜像的情况。2。队列为空。
代码
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root==None:
return True
def compare(root1,root2):
if not root1 and not root2:
return True
if not root1 or not root2:
return False
if root1.val!=root2.val:
return False
return compare(root1.left,root2.right) and compare(root1.right,root2.left)
class Solution(object):
def isSymmetric(self, root):
if not root or not (root.left or root.right):
return True
Queue=[root.left,root.right]
while Queue:
elem1=Queue.pop(0)
elem2=Queue.pop(0)
if not elem1 and not elem2:
continue
if not elem1 or not elem2:
return False
if elem1.val!=elem2.val:
return False
Queue.append(elem1.left)
Queue.append(elem2.right)
Queue.append(elem1.right)
Queue.append(elem2.left)
return True
参考链接:https://leetcode-cn.com/problems/symmetric-tree/solution/dong-hua-yan-shi-101-dui-cheng-er-cha-shu-by-user7/