if root一定要写,因为可能输入的时候是空的,这时候空对象是不可能有left或者right属性的,会报错
一种更简便的写法 class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root: self.invertTree(root.left) self.invertTree(root.right) root.left,root.right = root.right,root.left return root 栈的做法 class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ stack = [root] while stack: top = stack.pop() if top: top.left,top.right = top.right,top.left stack.append(top.left) stack.append(top.right) return root