python extend怎么用_正确使用extend?

本文探讨了二叉树节点的遍历方法,并详细解释了如何递归地收集叶子节点与内部节点的数据,同时解决了递归过程中列表重置的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class BTNode(object):

"""A node in a binary tree."""

def __init__(self, item, left=None, right=None):

"""(BTNode, object, BTNode, BTNode) -> NoneType

Initialize this node to store item and have children left and right,

as well as depth 0.

"""

self.item = item

self.left = left

self.right = right

self.depth = 0 # the depth of this node in a tree

def __str__(self):

"""(BTNode) -> str

Return a "sideways" representation of the subtree rooted at this node,

with right subtrees above parents above left subtrees and each node on

its own line, preceded by as many TAB characters as the node's depth.

"""

# If there is a right subtree, add an extra TAB character in front of

# every node in its string representation, with an extra newline at the

# end (ready to be concatenated with self.item).

if self.right:

str_right = "\t" + str(self.right).replace("\n", "\n\t") + "\n"

else:

str_right = ""

# The string representation of self.item: if item is a string, use

# repr(item) so that quotes are included and special characters are

# treated correctly -- just like in a list; else use str(item).

if isinstance(self.item, str):

str_item = repr(self.item)

else:

str_item = str(self.item)

# If there is a left subtree, add an extra TAB character in front of

# every node in its string representation, with an extra newline at the

# beginning (ready to be concatenated with self.item).

if self.left:

str_left = "\n\t" + str(self.left).replace("\n", "\n\t")

else:

str_left = ""

# Put the right subtree above the root above the left subtree.

return str_right + str_item + str_left

def leaves_and_internals(self):

"""(BTNode) -> ([object], [object])

Return a pair of lists: (list of all the items stored in the leaves of

the subtree rooted at this node, list of all the items stored in the

internal nodes of the subtree rooted at this node).

"""

#Leaf: Doesn't have children

#Internal Node: Has children

leaf = []

internal = []

if not self.left and not self.right:

leaf.append(self.item)

if self.left is not None:

internal.append(self.item)

if self.right is not None:

self.right.leaves_and_internals()

self.left.leaves_and_internals()

elif self.right is not None:

internal.append(self.item)

self.right.leaves_and_internals()

print(leaf, internal)

return leaf, internal

BTNode类是我们无法编辑的起始代码。我的职责是按照给定的docstring为leaves_和_间隔编写代码。我目前唯一的问题是不知道如何使用extend正确地递归地组合列表。在

我的测试块看起来是这样的:

^{pr2}$

我的输出是这样的:[8] []

[] [6]

[] [4]

[] [2]

正确的输出应该如下所示(顺序不重要):[8] [6, 4, 2]

如何正确地使用extend,使leaf和internal不会在每次递归时都重置回空列表?我知道我必须有第二组扩展列表,只是不确定如何实现它。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值