【发布时间】:2018-04-25 02:46:13
【问题描述】:
这是一个关于修剪二叉树的算法。例如:
1 1
/ \ \
0 1 => 1
/ \ / \ \
0 00 1 1
我已经有了处理这个问题的递归方法,就是
def pruneTree_recursion(root):
if root is None:
return None
root.left = pruneTree_recursion(root.left)
root.right = pruneTree_recursion(root.right)
return root if root.val == 1 or root.left or root.right else None
但是我也有另外一种方法来处理这个问题,也是使用postorder来逐个切假。
def pruneTree(root):
def postorder(root, orderlist):
if root:
postorder(root.left, orderlist)
postorder(root.right, orderlist)
orderlist.append(root)
return orderlist
orderlist = postorder(root, [])
for node in orderlist:
if node.val == 0:
if (node.left is None) and (node.right is None):
node = None # May be the problem is here [1]
return root
如果我将 [1] 中的代码更改为 node.val = 88,它可以工作。每个需要削减的地方都会变成88。但是当我使用node = None时。它不起作用。这棵树仍然是原来的那棵。这是怎么出现的?如何修复它。感谢任何可以帮助我的人。
【问题讨论】:
-
在
for node in orderlist:中,node是一个变量,它一个一个地接受列表中的元素。分配给它对列表绝对没有影响,它不是您似乎期望的列表中特定位置的别名。 -
是的。你说的对。我对其进行了测试,这就是为什么我的程序不起作用的原因。非常感谢。我真是个白痴:)。
标签: python python-3.x algorithm binary-tree inorder