剑指offer 二叉树的镜像

剑指offer 牛客网 二叉树的镜像

# -*- coding: utf-8 -*-
"""
Created on Mon Apr  8 17:26:00 2019

@author: Administrator

操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:源二叉树 
            8
           /  \
          6   10
         / \  / \
        5  7 9 11
        镜像二叉树
            8
           /  \
          10   6
         / \  / \
        11 9 7  5
"""

# -*- coding:utf-8 -*-
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if root:            
            root.left,root.right = root.right,root.left
            self.Mirror(root.left)
            self.Mirror(root.right)
        return root
    def Inorder(self,root):
        if root:
            print(root.val)
            self.Inorder(root.left)
            self.Inorder(root.right)

if __name__ == '__main__':
    solution = Solution()
    node_left = TreeNode(5)
    node_right = TreeNode(7)
    root_left = TreeNode(6)
    root_left.left = node_left
    root_left.right = node_right
    
    node_left = TreeNode(9)
    node_right = TreeNode(11)
    root_right = TreeNode(10)
    root_right.left = node_left
    root_right.right = node_right
    
    root = TreeNode(8)
    root.left = root_left
    root.right = root_right

    res = solution.Mirror(root)    
    solution.Inorder(res)

 

posted @ 2019-04-09 09:32  weilongyitian  阅读(114)  评论(0编辑  收藏  举报