【问题标题】:How to determine if a Binary Tree node is a Left or Right child?如何确定二叉树节点是左孩子还是右孩子?
【发布时间】:2015-03-30 19:37:30
【问题描述】:

我有一个简单的 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 ?

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

【问题讨论】:

    标签: python tree binary-tree binary-search-tree


    【解决方案1】:

    使用 parent 属性并测试内存引用是否父母的左右和孩子在内存中的引用相同。无论如何,您将需要一个父属性来遍历树。

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

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2022-08-11
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多