剑指offer笔记-5.二叉树的镜像

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

#class TreeNode:
#    def __init__(self,x):
#        self.val = x
#        self.left = None
#        self.right = None
class Solution:
        def Mirror(self,root):
                if root != None:
                        root.left, root.right = root.right,root.left
                        self.Mirror(root.left)
                        self.Mirror(root.right)

解法2:

class Solution:
        def Mirror(self,root):
                if not root:
                        return root
                if not root.left and not root.right:
                        return root
                if root.left or root.right:
                        t = root.right
                        root.right = root.left
                        root.left = root.right
                self.Mirror(root.left)
                self.Mirror(root.right)
                return root

Python中的矩阵运算知识:
https://www.cnblogs.com/chamie/p/4870078.html

5、顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.


扩展题:逆时针打印矩阵


笔记:这个比较难,自己想的过程很复杂,并且不一定正确,讨论区答案,很好的题目,实践学到很多~感谢大神们的解答
解法1:排名第二,一直关注的一个大神的答案,思路是先取矩阵第一行,剩余矩阵行列互换,再行翻转,所得矩阵取第一行,matrix.pop(0),剩余矩阵再行列互换,行翻转,直至剩余矩阵不再是矩阵。

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        result=[]
        while matrix:
            result=result+matrix.pop(0)
            if not matrix:
                break
            matrix=self.turn(matrix)
        return result
    def turn(self, matrix):
        r=len(matrix)
        c=len(matrix[0])
        B=[]
        for i in range(c):
            A=[]
            for j in range(r):
                A.append(matrix[j][i])
            B.append(A)
        B.reverse()
        return B

解法排名第一的用了xrange函数,因为是python2中,不熟悉,没看懂,所以放过~

总结:速度太慢了,但是一道好的题目学习到很多,加油~
争取把扩展题写出来贴上~

猜你喜欢

转载自blog.csdn.net/Leia21/article/details/89048535