generating a binary tree from given data in python

眉间皱痕 提交于 2019-12-05 19:20:40

This does sound like homework, so I won't write code, but here are a couple of hints:

  1. This could be done even if your triangle were written as a list, like 0 1 2 3 4 5 6 7 8 9

  2. Because it seems like this is a full binary tree (assuming your triangle is wrong and the third row is actually supposed to be 3 4 5 6), you could maintain a parents queue whose head is the next parent that needs children. Note that I am specifically not recommending recursion.

A full binary tree is one where each non-leaf node has exactly two children. If this is not supposed to be a full binary tree, then there is no deterministic way to interpret the problem (since each of node 1 and 2 could have 1 or 2 children, given your picture).

For such list:

a = 'aBCdef'

The program below generates the following structure:

- a -
- B C
B C -
- d e
d e f
e f -

Code (input list is assumed to correspond to a 'complete' triangular):

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

    def __unicode__(self):
        return '%s %s %s' % (
                self.left.data if self.left or '-', 
                self.data, 
                self.right.data if self.right or '-')


nodelist = [Node(c) for c in a]

i,y = 0,1

while True:
    for x in range(y):
        nodelist[i].left = nodelist[i-1] if x!=0 else None
        nodelist[i].right = nodelist[i+1] if x!=y-1 else None
        i+=1
    if i<len(a):
        y+=1
    else:
        break

for n in nodelist:
    print unicode(n)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!