问题描述
问题分析
这个问题是上一篇博客的后继,构造二叉树的过程采用递归即可
首先是节点的结构
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
接着按照递归进行左右子树求解,最后进行连接
def generate_trees(start, end):
global tear
tear = end
if start > end:
return [None, ]
all_trees = []
for i in range(start, end + 1): # pick up a root
# all possible left subtrees if i is choosen to be a root
left_trees = generate_trees(start, i - 1)
# all possible right subtrees if i is choosen to be a root
right_trees = generate_trees(i + 1, end)
# connect left and right subtrees to the root i
for l in left_trees:
for r in right_trees:
current_tree = TreeNode(i)
current_tree.left = l
current_tree.right = r
all_trees.append(current_tree)
return all_trees
问题存在于输出环节,要求以列表形式输出,并且遍历过程采取的是层次遍历,多种遍历方式参考二叉树遍历
除此之外,关于null的输出问题,当所有非null的节点输出完成之后,后续的null就不用继续输出了,因此这也是需要处理的一部分
因此输出部分的代码为
def treeToArray(root):
global full # 要修改全局变量,必须加上global声明
global temp_arr
global all_arr
# if full is 0:
# return
#
# if root is None:
# temp_arr.append('None')
# return
# else:
# temp_arr.append(root.val)
# full -= 1
#
# if root.left is None and root.right is None:
# return
#
# treeToArray(root.left)
# treeToArray(root.right)
myqueue = []
if root is None:
return
myqueue.append(root)
while len(myqueue) != 0:
if full is 0:
break
node = myqueue.pop(0)
if node is None:
temp_arr.append("null")
else:
temp_arr.append(node.val)
full -= 1
myqueue.append(node.left)
myqueue.append(node.right)
trees = generate_trees(1, n) if n else []
# e.g. if n = 3, we should consider the cases of roots as 1 or 2 or 3, so index start from 1
for tree in trees:
global all_arr
global temp_arr
global full
full = tear
temp_arr = []
treeToArray(tree)
all_arr.append(temp_arr)
return all_arr
treeToArray函数将数转为array形式,输入根结点,输出list(注释部分是一开始写错的,写成了先序遍历)
下面的for循环一次传入树的根结点,最后合并到all_arr中并返回
这里想要记录的是global全局变量与闭包的问题。由于对python不熟悉,因此在这些问题上犯了错误
关于global的作用这里不做赘述,一篇参考
稍作提示就是:
当你想要修改全局变量的值时,必须在局部区域内声明global
假如你直接选择创建变量(var = value),那么生成的就是局部变量
一旦声明了global,后续代码操作的就都是外部变量
问题在于global与闭包同时存在时
例子:
def func():
num = 100
def func2():
global num
num = 700
print(num)
func2()
print(num)
func()
print(num)
输出为:
假如:
def func():
num = 100
# def func2():
# global num
# num = 700
# print(num)
#
# func2()
print(num)
func()
print(num)
输出为:
所以说,在闭包内的变量加上global,相当于创建了全局变量