- Reshape the Matrix
思路:調(diào)用numpy庫(kù)就能實(shí)現(xiàn)矩陣的變形原在,但是生成的結(jié)果要從“numpy.ndarray”多維數(shù)組轉(zhuǎn)換為“l(fā)ist”列表類型牲芋,【列表姑蓝、數(shù)組砾隅、矩陣】
import numpy as np
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
try:
return np.reshape(nums, (r, c)).tolist()
except:
return nums
- Trim a Binary Search Tree
思路:二叉搜索樹(shù)規(guī)定了左子樹(shù)的值一定要小于右子樹(shù)宣渗。所以中序遍歷BST得到的是遞增的序列
class Solution(object):
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
if not root:
return None
if L > root.val:
return self.trimBST(root.right,L,R)
elif root.val > R:
return self.trimBST(root.left,L,R)
root.left = self.trimBST(root.left,L,R)
root.right = self.trimBST(root.right,L,R)
return root
復(fù)習(xí)一下先序(根左右)吨铸、中序(左根右)行拢、后序(左右根)遍歷二叉樹(shù)
image.png
先序輸出:
A B D G H E C K F I J
中序輸出:
G D H B E A K C I J F
后序輸出:
G H D E B K J I F C A