2015-03-30 43 views
2

我有一個簡單的Tree數據結構,但是,我想實現兩個方法,名爲isLeftChildisRightChild如何確定一個二叉樹節點是左邊還是右邊的孩子?

問題是我很難理解樹木。概念和一般過程尚未完全掌握。

這裏是我的簡單的樹至今:

class Node(object): 
    ''' A tree node. ''' 
    def __init__(self, data): 
     self.left = None 
     self.right = None 
     self.data = data 

    def isLeftChild(self): 
     ''' Returns True if the node is a left child, else False. ''' 
     pass 

    def isRightChild(self): 
     ''' Returns True if the node is a right child, else False. ''' 
     pass 

    def insert(self, data): 
     ''' Populate the tree. ''' 
     if self.data: 
      if data < self.data: 
       if self.left is None: 
        self.left = Node(data) 
       else: 
        self.left.insert(data) 
      elif data > self.data: 
       if self.right is None: 
        self.right = Node(data) 
       else: 
        self.right.insert(data) 
     else: 
      self.data = data 

    def printTree(self): 
     ''' Display the tree. ''' 
     if self.left: 
      self.left.printTree() 
     print self.data 
     if self.right: 
      self.right.printTree() 

def main(): 
    root = Node(8) 
    root.insert(2) 
    root.printTree() 

main() 

怎樣纔可以有一個節點確定它是否是一個左子或右子(不參照其data

我不知道我需要添加到我的樹,以確定這一點。

回答

3

使用父屬性並測試內存引用,如果父母的右邊或左邊與內存中的子引用相同。無論如何,你將需要一個父屬性來遍歷樹。

return self is self.parent.left # in the isLeftChild 
相關問題