《剑指offer》面试题15:二叉树的镜像(Python)

 

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述:

二叉树的镜像定义:源二叉树 
    	    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==None:
            return None
        root.left,root.right=root.right,root.left
        
        
        self.Mirror(root.left)
        self.Mirror(root.right)
        #关键是我不写返回root这个程序也能运行
        return root

这个题目的意思是首先交换root下面的两个节点,然后交换root下下层的两个节点,最后返回新的root的树的根节点。

解法二:构造新的二叉树,但是这个方法可以我们自行学习而不用在这个题目上,因为这个题目让我们返回的是原来的二叉树而非新的二叉树,不然测试用例的通过情况为0,代码如下:

# -*- 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 == None:
            return None
        newTree = TreeNode(root.val)
      #首先构造新的节点,然后将新的节点下面的两个子树分别进行替换,更改方向 newTree.right
= self.Mirror(root.left) newTree.left = self.Mirror(root.right) return newTree

 

posted @ 2020-08-27 08:11  Geeksongs  阅读(202)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.