牛客-剑指offer系列题解:二叉树的镜像

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。

1、问题描述:

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

2、数据结构:

二叉树

3、题解:
处理根节点,处理左子树,处理右子树。

# -*- 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 not root:
            return None
        #处理根节点
        root.left,root.right = root.right,root.left
        #处理左子树
        self.Mirror(root.left)
        #处理右子树
        self.Mirror(root.right)
        return root

或者:

class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if not root:
            return
        root.left,root.right = self.Mirror(root.right),self.Mirror(root.left)
        return root

4、复杂度分析:

时间复杂度:O(N),N结点数量

空间复杂度:O(N)


版权声明:本文为weixin_42042056原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。