Invert Binary Tree

来源:互联网 发布:淘宝客服议价话术 编辑:程序博客网 时间:2024/06/11 05:39

题目:

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9
to
     4   /   \  7     2 / \   / \9   6 3   1
解题思路:

此题就是对树的结构一些应用以及对递归的考察。解答此题时,破费一些时间,说明对树与递归还未完全 熟悉。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    # @param {TreeNode} root
    # @return {TreeNode}
    def invertTree(self, root):
        if root==None or (root.left==None and root.right==None):
            return root
        elif root.left!=None and root.right!=None:
            root.left, root.right=self.invertTree(root.right), self.invertTree(root.left)
            return root
        elif root.left!=None:
            root.right = self.invertTree(root.left)
            root.left = None
            return root
        elif root.right!=None:
            root.left = self.invertTree(root.right)
            root.right = None
            return root
        

0 0