Description
操作给定的二叉树,将其变换为源二叉树的镜像。
Solutions
还是要花时间总结出规律,其中一个观察点是每圈开始的第一个点的坐标是 $ (x, x)$,
# -*- coding:utf-8 -*-
class Solution:
def printMatrixInCircle(self, matrix, start, rows, columns):
res = []
endX=columns-1-start
endY=rows-1-start
# 从左到右打印一行
for i in range(start,endX+1):
res.append(matrix[start][i])
# 从上到下打印一列
if start<endY:
for i in range(start+1,endY+1):
res.append(matrix[i][endX])
# 从右到左打印一行
if start<endX and start<endY:
for i in range(endX-1,start-1,-1):
res.append(matrix[endY][i])
# 从下到上打印一列
if start<endX and start<endY-1:
for i in range(endY-1,start,-1):
res.append(matrix[i][start])
return res
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
if matrix is None:
return None
res = []
rows = len(matrix)
columns = len(matrix[0])
start = 0
while rows > 2 * start and columns > 2 * start:
res += self.printMatrixInCircle(matrix, start, rows, columns)
start += 1
return res
同样是这种方式,还有一种通过参数传值传递的写法,似乎更省空间??
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
if not matrix or len(matrix)<=0 or len(matrix[0])<=0:
return
start=0
rows=len(matrix)
columns=len(matrix[0])
res=[]
while(columns>start*2 and rows>start*2):
self.printMatrixInCircle(matrix,columns,rows,start,res)
start += 1
return res
def printMatrixInCircle(self,matrix,columns,rows,start,res):
endX=columns-1-start
endY=rows-1-start
# 从左到右打印一行
for i in range(start,endX+1):
res.append(matrix[start][i])
# 从上到下打印一列
if start<endY:
for i in range(start+1,endY+1):
res.append(matrix[i][endX])
# 从右到左打印一行
if start<endX and start<endY:
for i in range(endX-1,start-1,-1):
res.append(matrix[endY][i])
# 从下到上打印一列
if start<endX and start<endY-1:
for i in range(endY-1,start,-1):
res.append(matrix[i][start])
还有一种黑魔法解法:
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
return matrix and list(matrix.pop(0))+self.printMatrix(zip(*matrix)[::-1])