class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
queue = collections.deque([root])
result = []
while queue:
level = []
for _ 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)
result.append(level)
return result
226.翻转二叉树
要点
每个节点的左右孩子都翻转一遍即可。
递归法:采用前序遍历或者后序遍历递归都可以。
迭代法和层序遍历也都可以实现。
代码
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:#递归法
return True
return self.compare(root.left,root.right)
def compare(self, left, right):
if left and not right: return False
elif not left and right: return False
elif not left and not right: return True
elif left.val != right.val: return False
outside = self.compare(left.left, right.right)
inside = self.compare(left.right, right.left)
return outside and inside
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:#队列法,相比递归更好理解
return True
queue = collections.deque()
queue.append(root.left)
queue.append(root.right)
while queue:
leftNode = queue.popleft()
rightNode = queue.popleft()
if not leftNode and not rightNode:
continue
if not leftNode or not rightNode or leftNode.val != rightNode.val:
return False
queue.append(leftNode.left)
queue.append(rightNode.right)
queue.append(leftNode.right)
queue.append(rightNode.left)
return True