leetcode 226翻转二叉树(剑指offer.二叉树的镜像)
初级递归
1 class Solution: 2 def invertTree(self, root: TreeNode) -> TreeNode: 3 if not root: 4 return 5 root.left,root.right=root.right,root.left 6 self.invertTree(root.left) 7 self.invertTree(root.right) 8 return root
一行递归
1 class Solution: 2 def invertTree(self, root: TreeNode) -> TreeNode: 3 if not root: 4 return 5 root.left,root.right=self.invertTree(root.right),self.invertTree(root.left) 6 return root
辅助栈
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return 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