倒置二叉树
答案:递归方法
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root == None: return None 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, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root==None or root.left==root.right==None: return root parent = [root] while len(parent): children = [] for node in parent: node.left, node.right = node.right, node.left if node.left: children.append(node.left) if node.right: children.append(node.right) parent = children return root