How to implement a binary search tree in Python?

前端 未结 18 2175
眼角桃花
眼角桃花 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:17

    Just something to help you to start on.

    A (simple idea of) binary tree search would be quite likely be implement in python according the lines:

    def search(node, key):
        if node is None: return None  # key not found
        if key< node.key: return search(node.left, key)
        elif key> node.key: return search(node.right, key)
        else: return node.value  # found key
    

    Now you just need to implement the scaffolding (tree creation and value inserts) and you are done.

提交回复
热议问题