226. Invert Binary Tree

倒置二叉树
答案:

递归方法

# 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 = None

class 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

 

posted @ 2016-03-07 19:31  python挖掘  阅读(161)  评论(0编辑  收藏  举报