1. 程式人生 > >Lintcode 175. 翻轉二叉樹

Lintcode 175. 翻轉二叉樹

我的程式碼:

class Solution:
    """
    @param root: a TreeNode, the root of the binary tree
    @return: nothing
    """
    def invertBinaryTree(self, root):
        if root.left == None and root.right == None:
            return
        if root.left != None and root.right == None://這裡一定要改成elif,因為左右子節點交換後會變成下面的if的情況,導致再一次交換,所以要改成elif
            root.right = root.left
            root.left = None
            self.invertBinaryTree(root.right)
        if root.left == None and root.right != None://包括這裡
            root.left = root.right
            root.right = None
            self.invertBinaryTree(root.left)
        else:
            temp = root.left
            root.left = root.right
            root.right = temp
            self.invertBinaryTree(root.left)
            self.invertBinaryTree(root.right)

修改後程式碼:

class Solution:
    """
    @param root: a TreeNode, the root of the binary tree
    @return: nothing
    """
    def invertBinaryTree(self, root):
        if root.left == None and root.right == None:
            return
        elif root.left != None and root.right == None:
            root.right = root.left
            root.left = None
            self.invertBinaryTree(root.right)
        elif root.left == None and root.right != None:
            root.left = root.right
            root.right = None
            self.invertBinaryTree(root.left)
        else:
            temp = root.left
            root.left = root.right
            root.right = temp
            self.invertBinaryTree(root.left)
            self.invertBinaryTree(root.right)