Lintcode 175. 두 갈래 나무를 뒤집다

1637 단어
내 코드:
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)

좋은 웹페이지 즐겨찾기