How to implement a binary search tree in Python?

前端 未结 18 2144
眼角桃花
眼角桃花 2020-11-30 22:25

This is what I\'ve got so far but it is not working:

class Node:
    rChild,lChild,data = None,None,None

    def __init__(self,key):
        self.rChild = N         


        
18条回答
  •  庸人自扰
    2020-11-30 23:06

    A simple, recursive method with only 1 function and using an array of values:

    class TreeNode(object):
    
        def __init__(self, value: int, left=None, right=None):
            super().__init__()
            self.value = value
            self.left = left
            self.right = right
    
        def __str__(self):
            return str(self.value)
    
    
    def create_node(values, lower, upper) -> TreeNode:
        if lower > upper:
            return None
    
        index = (lower + upper) // 2
    
        value = values[index]
        node = TreeNode(value=value)
        node.left = create_node(values, lower, index - 1)
        node.right = create_node(values, index + 1, upper)
    
        return node
    
    
    def print_bst(node: TreeNode):
        if node:
            # Simple pre-order traversal when printing the tree
            print("node: {}".format(node))
            print_bst(node.left)
            print_bst(node.right)
    
    
    
    if __name__ == '__main__':
        vals = [0, 1, 2, 3, 4, 5, 6]
        bst = create_node(vals, lower=0, upper=len(vals) - 1)
        print_bst(bst)
    

    As you can see, we really only need 1 method, which is recursive: create_node. We pass in the full values array in each create_node method call, however, we update the lower and upper index values every time that we make the recursive call.

    Then, using the lower and upper index values, we calculate the index value of the current node and capture it in value. This value is the value for the current node, which we use to create a node.

    From there, we set the values of left and right by recursively calling the function, until we reach the end state of the recursion call when lower is greater than upper.

    Important: we update the value of upper when creating the left side of the tree. Conversely, we update the value of lower when creating the right side of the tree.

    Hopefully this helps!

提交回复
热议问题