2017-05-02 74 views
2

我有我的代碼如下,我正在讀取鏈接列表中的數據並從中創建一個二叉樹。我在這裏使用一個列表(q)並添加self.top當我打印q的值時,它給了我一些地址。將Linklist節點添加到隊列

我不知道那個地址是什麼?

接下來,當我彈出隊列並將其分配給父母並打印parent.root時,它將打印出我的值。如何在這裏工作?

class createnode: 
    def __init__(self,val): 
     self.data=val 
     self.next=None  ##Creation of Node in link list 
class createbinarytree: 
    def __init__(self,data): 
     self.root=data 
     self.left=None 
     self.right=None  ##Creation of binary tree nodes 
class createlist: 
    def __init__(self, data = None): 
     self.head = None  
     self.top = None  
    def push(self,val):   
     node=createnode(val) 
     if self.head is None: 
      self.head=node 
     else: 
      node.next=self.head ##Pushing the node to a link list 
      self.head=node 
    def convertedtree(self): 
     q=[] 
     if self.head is None: ##Function to convert link list to binary tree 
      self.top = None 
      return 
     self.top=createbinarytree(self.head.data) 
     q.append(self.top) ##Printing q here gives some kind off address 
     self.head=self.head.next 
     while(self.head): 
     self.parent=q.pop(0) 
     self.Leftchild=None 
     self.Rightchild=None 
     self.Leftchild=createbinarytree(self.head.data) 
     q.append(self.Leftchild) 
     self.head=self.head.next 
     if(self.head): 
      self.Rightchild=createbinarytree(self.head.data) 
      q.append(self.Rightchild) 
      self.head=self.head.next 
     self.parent.left=self.Leftchild 
     self.parent.right=self.Rightchild 

     def printlist(self): 
     temp=self.head 
     while(temp): 
      print(temp.data) 
      temp=temp.next 

conv=createlist(); 
conv.push(10) 
conv.push(20) 
conv.push(30) 
conv.printlist() 
conv.convertedtree() 
+0

你有頂,頭和根。我不認爲你可以發佈足夠的代碼來運行一個簡單的例子嗎?如果沒有足夠的信息來回答,很難說出你的問題,尤其是語言障礙。您可能會意外地解決問題,同時嘗試隔離[mcve]中的問題 –

+0

@KennyOstrom更新了問題並添加了完整代碼 – codaholic

+0

Nice更新。我不知道你以前問過什麼。你似乎對什麼是樹和什麼是節點不一致,但這與實際問題無關,這就是爲什麼python會打印出無用的信息,而不是明確說明對象數據成員是什麼。答案是,你的班級必須告訴Python如何做到這一點。 –

回答

0

您正在打印的清單。如果這個列表是[「this」,「is」,「a」,「list」,「of」,「strings」],那麼你就會明白你的期望。但是因爲它是一個類對象的列表,它必須以某種方式打印它們。因此它默認打印類的名稱和實例的地址。

你可能應該在代碼中有「打印q」,因爲這就是你所問的。我補充說,以後每次q改變,並得到這個:

30 
20 
10 
[] 
[<__main__.createbinarytree instance at 0x02CB9A58>] 
[] 
[<__main__.createbinarytree instance at 0x02CB9A30>] 
[<__main__.createbinarytree instance at 0x02CB9A30>, <__main__.createbinarytree instance at 0x02CB9A08>] 

如果你的類提供了一種方法來轉換爲字符串,那麼你可以把它打印更多有用的信息。見What is the purpose of __str__ and __repr__ in Python?

class createbinarytree: 
    def __init__(self,data): 
     self.root=data 
     self.left=None 
     self.right=None  ##Creation of binary tree nodes 
    def __repr__(self): 
     return "<Node value=" + str(self.root) + ">" 

然後我得到的輸出喜歡這個

30 
20 
10 
[] 
[<Node value=30>] 
[] 
[<Node value=20>] 
[<Node value=20>, <Node value=10>] 
+0

我找到了另外一種方法。你的方法也是正確的,但我發現這裏解釋的很簡單。例如:** for obj in q:print obj.root **。它讓我輸出了所有推送的根值。無論如何感謝您深入解釋這個概念。 – codaholic