27:二叉树的镜像(剑指offer第2版)LeetCode226. 翻转二叉树

36 篇文章 0 订阅

1、题目描述

27二叉树的镜像https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/

226翻转二叉树https://leetcode-cn.com/problems/invert-binary-tree/

两题一模一样!

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

输入描述:

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

相似题:LeetCode101. 对称二叉树(递归和迭代) https://blog.csdn.net/IOT_victor/article/details/107117445

2、代码详解

力扣版的题解(动画理解)+辅助栈写法

https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/mian-shi-ti-27-er-cha-shu-de-jing-xiang-di-gui-fu-/

https://leetcode-cn.com/problems/invert-binary-tree/solution/dong-hua-yan-shi-liang-chong-shi-xian-226-fan-zhua/

递归法如下

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def mirrorTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root == None:
            return None
        tmp = root.left  # 暂存 root 的左子节点

        # 下两句顺序不能换,因为tmp的交换问题。当然也可以tmp = root.right,下两句便随之改变
        # 递归 右子节点 mirrorTree(root.right) ,并将返回值作为 root 的 左子节点
        root.left = self.mirrorTree(root.right)
        # 递归 左子节点 mirrorTree(tmp) ,并将返回值作为 root 的 右子节点
        root.right = self.mirrorTree(tmp)

        return root

需要判断输入的结点为空或者输入的结点没有子树的情况。

# -*- coding:utf-8 -*-
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    # 递归实现
    def Mirror(self, root):
        if root == None:
            return
        if root.left == None and root.right == None:
            return root

        pTemp = root.left
        root.left = root.right
        root.right = pTemp

        self.Mirror(root.left)
        self.Mirror(root.right)

pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode3 = TreeNode(10)
pNode4 = TreeNode(5)
pNode5 = TreeNode(7)
pNode6 = TreeNode(9)
pNode7 = TreeNode(11)

pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7

S = Solution()
S.Mirror(pNode1)
print(pNode1.right.left.val)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值