首页 > 其他 > 详细

剑指offer 二叉树的镜像

时间:2019-04-09 10:46:57      阅读:173      评论:0      收藏:0      [点我收藏+]

剑指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)

 

剑指offer 二叉树的镜像

原文:https://www.cnblogs.com/missidiot/p/10674931.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!