简体   繁体   中英

Populating a binary search tree?

I'm trying to create a binary search tree from the following class:

class Tree(object):
    def __init__(self):
        self.data = None
        self.left = None
        self.right = None

The following code should work on a list, cutting it in half and passing the halves off recursively. However, I'm getting the same node for both left and right.

def populatetree(words):#not working
   middle = len(words)//2
   root = Tree()
   root.data = wordlist[middle][0]

   if len(words) > 3:
      root.left = populatetree(words[:len(words)//2])
      root.right = populatetree(words[len(words)//2+1:])
   else:
      if middle!=0:
         root.left = Tree()
         root.left.data = words[0]
      if(len(words)==3):
         root.right = Tree()
         root.right.data = words[2]
   return root

Sample input:

['2', 'a', 'add', 'an', 'be', 'convert', 'integer', 'is', 'print', 'result', 'set', 'thank', 'the', 'to', 'variable', 'x1', 'y2', 'yes', 'you']'

Sample output:

['result']
['be', 'be']
['add', 'add', 'add', 'add']
['a', '2', 'a', '2', 'a', '2', 'a', '2']
['2', 'convert', 'set', 'x1']

where the output is being printed in a pyramidal format, in otherwords be and be belong to result , the first add and second add belong to be, and the next two adds belong to the other be , and so on and so forth. I've checked the actual data and tree.left.data and tree.right.data are in fact both be and be . This baffles me since the right sub tree shouldn't even be able to see be since I'm passing it the right half of the list .

Any idea what I need to do differently to populate the list properly?

It looks like Tree.data is being taken from something called "wordlist", which is undefined within the sample code you presented, and is not the argument to the function populatetree. Perhaps wordlist is the original list?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM