# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
调用函数时,加 self.函数名
list排序 nums.sort()
pre.next = l1 if l1 else l2 # 类似C++三目表达式,l1为真则l1,否则l2
list列表使用
def convertBST(self, root: TreeNode) -> TreeNode:
stack = [(root,1)]
sum = 0
while stack:
node, cmd = stack.pop()
if node is None:
continue
if cmd == 0:
sum += node.val
node.val = sum
else:
stack.append((node.left, 1))
stack.append((node, 0))
stack.append((node.right, 1))
return root
python定义全局变量
self.sum =0
def convertBST(self, root: TreeNode) -> TreeNode:
if root == None:
return
self.val = 0
def dfs(root):
if root == None:
return
root.right = dfs(root.right)
self.val += root.val
root.val = self.val
root.left = dfs(root.left)
return root
return dfs(root)
python3交换
a, b = b, a # 类似C++ swap操作
list模拟栈
self.stackB = []
if self.stackB: # 判断是否为空
self.stackB[-1] # 取top()
self.stackB.append(x) # push操作
self.stackB.pop() # pop()操作
创建list
ary_len =len(prices)
dp= [0] * ary_len
import collections
d = collections.deque()
import collections
d = collections.deque()
d.append(1)
d.append(2)
print(d)
#输出:deque([1, 2])
d.appendleft(2)
d.clear()
x = d.pop()
x = d.popleft()
d.reverse()