# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
queue=collections.deque([root])
res=[]
if not root:
return []
while queue:
level=[]
for i in range(len(queue)):
cur=queue.popleft()
level.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
res.append(level)
return res
思路:先交换左右子节点,再反转左右子树
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
思路:若根节点为空,则一定是对称二叉树;比较左右子节点,若左右子节点都为空,则为对称二叉树,若存在其中一个节点为空,则不是对称二叉树;若左右子节点都存在,但是对应值不相等,也不是二叉树;若左右子节点都存在且对应值相等则判断左子树左节点和右子树右节点是否相等(外侧),左子树右节点与右子树左节点是否相等(内侧)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.compare(root.left,root.right)
def compare(self,left,right):
if left is None and right is None: return True
elif left is None or right is None: return False
elif left.val !=right.val: return False
outside=self.compare(left.left,right.right)
inside=self.compare(left.right,right.left)
issame=outside and inside
return issame