# 层序遍历 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution: definvertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root isNone: returnNone q = [root] while q: tmp = q q = [] for node in tmp: node.left, node.right = node.right, node.left if node.left: q.append(node.left) if node.right: q.append(node.right) return root
Go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//递归法 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcinvertTree(root *TreeNode) *TreeNode { if root == nil { returnnil } root.Left, root.Right = invertTree(root.Right), invertTree(root.Left) return root }
//递归法 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcisSymmetric(root *TreeNode)bool { return check(root, root) }
funccheck(p, q *TreeNode)bool { if p == nil && q == nil { returntrue } if p == nil || q == nil { returnfalse } return p.Val == q.Val && check(p.Left, q.Right) && check(p.Right, q.Left) }