学习日记-20190607

学习日记-2019年06月07日

从前序和后序中恢复二叉树

定义一个映射字典,把前序遍历中的值映射到中序遍历中

1
idx_map = {val:idx for idx,val in enumerate(inorder)}

从前序和后序中恢复二叉树

leetcode官方题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self,preorder,inorder):
"""
:param preorder: List[int]
:param inorder: List[int]
:return: TreeNode
"""

def helper(in_left=0, in_right=len(inorder)):
# 定义非局部变量pre_idx
nonlocal pre_idx
if in_left == in_right:
return None
# 前序遍历的元素作为根节点
root_val = preorder[pre_idx]
root = TreeNode(root_val)
# 在中序遍历中找左右子树
index = idx_map[root_val]
# 递归
pre_idx += 1
# 创建左子树
root.left = helper(in_left,index)
# 创建右子树
root.right = helper(index+1,in_right)
return root
# 从列表中的第一个元素开始遍历
pre_idx = 0
# 定义一个映射字典,即把前序遍历中的值映射到中序遍历中
idx_map = {val:idx for idx,val in enumerate(inorder)}
# print(helper().val)
return helper()
-----------------------------------------------------------------------------------------
一位大佬的题解
class Solution1(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
x = preorder.pop(0)
node = TreeNode(x)
i = inorder.index(x)
node.left = self.buildTree(preorder[:i], inorder[:i])
node.right = self.buildTree(preorder[i:], inorder[i + 1:])
return node
if __name__ == '__main__':
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
sol = Solution()
print(sol.buildTree(preorder,inorder))
打印:
<__main__.TreeNode object at 0x000001F306B63CF8>

关于二叉树的测试用例的构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[1, null, 2, 3] 是个串行化格式,表达了一个水平顺序遍历的二叉树,null则代表树枝没有节点
[1,2,3]
1
/ \
2 3
[1, null, 2, 3]
1
\
2
/
3
[5, 4, 7, 3, null, 2, null, -1, null, 9]
5
/ \
4 7
/ /
3 2
/ /
-1 9

因为在leetcode中不能使用nonlocal,于是我特意去了解了一下nonlocal和global的区别

在默认情况下,不允许修改嵌套的def作用域中的名称,修改嵌套作用域中的名称会引发错误

使用nonolocal进行修改

  • nonlocal语句在执行时,nonlocal声明的名称必须已经在一个嵌套的def作用域中赋值过,否则将会得到一个错误:不能通过在嵌套的作用域中赋值来创建变量
  • nonlocal限制作用域查找仅为嵌套的def,不会在嵌套的模块的全局作用域或所有def之外的内置作用域中查找

nolocal 的使用场景就比较单一,它是使用在闭包中的,使变量使用外层的同名变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def foo(func):
a = 1
print("外层函数a的值", a)
def wrapper():
func()
nonlocal a
a += 1
print("经过改变后,里外层函数a的值:", a)
return wrapper
@foo
def change():
print("nolocal的使用")

change()
------------------------------------------------
外层函数a的值 1
nolocal的使用
经过改变后,里外层函数a的值: 2

参考 https://zhuanlan.zhihu.com/p/41030153

Python中self参数

self指代对象本身,调用函数的时候要先实例化这个方法。再用实例.方法调用。

Appium+Python自动化测试

https://blog.csdn.net/zh175578809/article/details/76780054