如何确定二叉树节点是左孩子还是右孩子?

3

我有一个简单的树形数据结构,但是我想要实现两个方法,分别命名为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

我不确定需要在树中添加什么才能确定这一点。

1个回答

3

使用父属性,并测试父节点的内存引用是否与子节点的内存引用相同,可以判断子节点是在父节点的左侧还是右侧。无论如何,您都需要一个父属性来遍历树。

return self is self.parent.left # in the isLeftChild

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接