我有一个简单的树形数据结构,但是我想要实现两个方法,分别命名为isLeftChild
和isRightChild
。
问题在于,我对树形结构的理解非常困难。我还没有完全掌握这个概念和一般的过程。
这是我目前的简单树形结构:
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
)?
我不确定需要在树中添加什么才能确定这一点。