二叉树镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
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 not root:
return None
root.left, root.right = root.right, root.left
self.Mirror(root.left)
self.Mirror(root.right)
return root
顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
解题思路:
模拟魔方逆时针旋转的方法,一直做取出第一行的操作
代码:
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
result = []
while matrix:
result += matrix.pop(0)
if not matrix or not matrix[0]:
break
matrix = self.turn(matrix)
return result
def turn(self, matrix):
newmat = []
row = len(matrix)
col = len(matrix[0])
for i in range(col):
newmat1=[]
for j in range(row):
newmat1.append(matrix[j][i])
newmat.append(newmat1)
newmat.reverse()
return newmat
包含min函数的栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
解题思路:
设计两个栈:Stack和StackMin,一个普通的栈,另外一个存储push进来的最小值,
每次压入的数据newNum都push进Stack中,然后判断StackMin是否为空,如果为空那也把newNum同步压入StackMin里;
如果不为空,就先比较newNum和StackMin中栈顶元素的大小,如果newNum较大,那就不压入StackMin里,只压入一个最小值。
否则就同步压入StackMin里。
弹出时,同步弹出,这是一个栈结构。
代码:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.minstack = []
def push(self, node):
# write code here
self.stack.append(node)
if self.minstack == [] or node < self.min():
self.minstack.append(node)
else:
self.minstack.append(self.min())
def pop(self):
# write code here
if self.minstack == [] or self.stack == []:
return None
self.minstack.pop()
self.stack.pop()
def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.minstack[-1]