python构造一个二叉树_在python中从列表构造二叉树的最佳方法

实现解决方案的一种方法是:创建一个树节点列表,每个节点的索引位置与原始数据列表相对应。然后,我们可以修复左右连接。在import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

class Tree(object):

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

self.data = data

self.left = left

self.right = right

def __repr__(self):

left = None if self.left is None else self.left.data

right = None if self.right is None else self.right.data

return '(D:{}, L:{}, R:{})'.format(self.data, left, right)

def build_tree_breadth_first(sequence):

# Create a list of trees

forest = [Tree(x) for x in sequence]

# Fix up the left- and right links

count = len(forest)

for index, tree in enumerate(forest):

left_index = 2 * index + 1

if left_index < count:

tree.left = forest[left_index]

right_index = 2 * index + 2

if right_index < count:

tree.right = forest[right_index]

for index, tree in enumerate(forest):

logger.debug('[{}]: {}'.format(index, tree))

return forest[0] # root

def main():

data = [3, 5, 2, 1, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14]

root = build_tree_breadth_first(data)

print 'Root is:', root

if __name__ == '__main__':

main()

输出:

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值