226. Invert Binary Tree

226. Invert Binary Tree_第1张图片
image.png

遍历一遍保存下来,然后再填进去是可以做的,但是这里可以直接递归来做

# 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 not root: return root
        l = self.invertTree(root.left)
        r = self.invertTree(root.right)
        root.left = r
        root.right = l
        return root

你可能感兴趣的:(226. Invert Binary Tree)