[英]Printing all paths from a binary tree with python
所以我有一个非常愚蠢的问题,我似乎无法弄清楚。 我只是想打印所有路径以及它们是如何使用前序遍历从二叉树形成的。 为此,我将每个值存储在数据结构中。 我的问题是,为什么在途中存储每个值时使用字符串与使用列表时的行为会发生变化?
对于具有以下定义的二叉树:
class BinaryTree:
def __init__(self, value, left_child=None, right_child=None):
self.value = value
self.left_child = left_child
self.right_child = right_child
left_branch = BinaryTree(5, BinaryTree(3, BinaryTree(7), BinaryTree(10)))
right_branch = BinaryTree(8, None, BinaryTree(4, BinaryTree(6), BinaryTree(9)))
root_tree = BinaryTree(1, left_branch, right_branch)
看起来像这样:
1
/ \
5 8
/ \
3 4
/ \ / \
7 10 6 9
使用字符串存储和打印值时:
def dfs(root, path):
if root:
path += str(root.value)
print(path)
dfs(root.left_child, path)
dfs(root.right_child, path)
dfs(root_tree, '')
我得到一个 output:
1
15
153
1537 <-- 1st
15310 <-- 2nd
18
184
1846 <-- 3rd
1849 <-- 4rd
没关系。
但是当我使用列表时:
def dfs(root, path):
if root:
path.append(root.value)
print(path)
dfs(root.left_child, path)
dfs(root.right_child, path)
dfs(root_tree, [])
它似乎没有做同样的事情,因为它只是将所有节点存储在同一路径上:
[1]
[1, 5]
[1, 5, 3]
[1, 5, 3, 7] <-- 1st
[1, 5, 3, 7, 10] <-- ???
[1, 5, 3, 7, 10, 8]
[1, 5, 3, 7, 10, 8, 4]
[1, 5, 3, 7, 10, 8, 4, 6]
[1, 5, 3, 7, 10, 8, 4, 6, 9]
我似乎无法理解为什么会这样。
发生这种情况是因为 string 是不可变类型,而 list 是可变的。
现在,当您在函数中(递归地)传递字符串时,只要它被修改,就会创建字符串的新实例,导致无法修改原始字符串。 字符串是不可变的
但是在列表中,对列表所做的修改不会在 function 调用中创建新实例。 Python 不介意更改原始列表,因为可以修改列表。 列表是可变的。
python在处理列表时的这种行为,可以说是memory优化,也可以说是OOP的纯精髓。
要对列表做同样的事情,只需像这样更改代码:
def dfs(root, path):
if root:
path.append(root.value)
print(path)
dfs(root.left_child, path.copy())
dfs(root.right_child, path.copy())
dfs(root_tree, [])
copy()
创建一个新列表 object 与非共享 memory 与原始列表
但是,这样做会使程序比以前消耗更多的 memory。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.