defstep(bst, left=None): if left isNone: left = flatten(bst.left) left.append(bst.val) right = flatten(bst.right) left.extend(right) return get_parent(bst) , left # <-- 需要get_parent
defstep(bst,parents,left=None): if left isNone: left = flatten(bst.left) left.append(bst.val) right = flatten(bst.right) left.extend(right) return parents[-1], parents[:-1], left
请注意,我们使用Python栈来表示父类,因此bst的直接父由最终元素parents[-1]给出。
作为一种简化,我们可以去掉bst参数,把它看作是推到栈上的最后一个父参数
1 2 3 4 5 6 7 8
defstep(parents, left=None): bst = parents.pop() # <-- bst = parents栈的顶部 if left isNone: left = flatten(bst.left) left.append(bst.val) right = flatten(bst.right) left.extend(right) return parents, left
defflatten(bst): left = [] parents = [] while bst isnotNone: parents.append(bst) bst = bst.left while parents: parents, left = step(parents, left) return left
defstep(parents, left): bst = parents.pop() left.append(bst.val) #-- begian partial evaluation bst1 = bst.right parents1 = [] while bst1 isnotNone: parents1.append(bst1) bst1 = bst1.left while parents1: parents1,left = step(parents1, left) #-- end partial evaluation return parents, left
defflatten(bst): left = [] parents = [] while bst isnotNone: parents.append(bst) bst = bst.left while parents: parents, left = step(parents, left) return left
defstep(parents, left): bst = parents.pop() left.append(bst.val) bst1 = bst.right while bst1 isnotNone: parents.append(bst1) bst1 = bst1.left return parents, left
对于我们旅程的最后一站 – 简化,让我们将step逻辑内嵌到基础函数中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defflatten(bst): left = [] parents = [] while bst isnotNone: parents.append(bst) bst = bst.left while parents: parents,left = parents,left bst = parents.pop() left.append(bst.val) bst1 = bst.right while bst1 isnotNone: parents.append(bst1) bst1 = bst1.left parents,left = parents,left return left
让我们消除琐碎参数绑定和返回值赋值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defflatten(bst): left = [] parents = [] while bst isnotNone: parents.append(bst) bst = bst.left while parents: # parents, left = parents, left bst = parents.pop() left.append(bst.val) bst1 = bst.right while bst1 isnotNone: parents.append(bst1) bst1 = bst1.left # parents, left = parents, left return left
最后,将重复的while循环变成一个局部函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
defflatten(bst): left = [] parents = [] defdescend_left(bst): while bst isnotNone: parents.append(bst) bst = bst.left descend_left(bst) while parents: bst = parents.pop() left.append(bst.val) descend_left(bst.right) return left