[1] update binary tree
This commit is contained in:
parent
fa690cac57
commit
f6478ee72e
|
|
@ -1,27 +1,53 @@
|
|||
def create_node(name,phone):
|
||||
return {"name": name, "phone": phone, "left": None, "right": None}
|
||||
|
||||
def dst_insert(root, name, phone):
|
||||
def bst_insert(root, name, phone):
|
||||
# Случай, если нет узлов
|
||||
if root is None:
|
||||
return create_node(name, phone)
|
||||
# Случай, если узел слева
|
||||
elif name < root["name"]:
|
||||
root["left"] = dst_insert(root["left"], name, phone)
|
||||
root["left"] = bst_insert(root["left"], name, phone)
|
||||
# Случай, если узел справа
|
||||
elif name > root["name"]:
|
||||
root["right"] = dst_insert(root["right"], name, phone)
|
||||
root["right"] = bst_insert(root["right"], name, phone)
|
||||
# Случай, если мы перезаписываем узел
|
||||
else:
|
||||
root["phone"] = phone
|
||||
return root
|
||||
|
||||
def dst_find(root, name):
|
||||
def bst_find(root, name):
|
||||
if root is None:
|
||||
return None
|
||||
elif root == root["name"]:
|
||||
return root["phone"]
|
||||
elif root < root["name"]:
|
||||
return dst_find(root["left"], name)
|
||||
return bst_find(root["left"], name)
|
||||
else:
|
||||
return dst_find(root["right"],name)
|
||||
return bst_find(root["right"],name)
|
||||
|
||||
def bst_delete(root, name):
|
||||
if root is None:
|
||||
return None
|
||||
elif root < root["name"]:
|
||||
return bst_delete(root["left"], name)
|
||||
elif root > root["name"]:
|
||||
return bst_delete(root["right"], name)
|
||||
# Узел, который надо удалить
|
||||
else:
|
||||
# Если нет потомков
|
||||
if (root["left"] and root["right"]) is None:
|
||||
return None
|
||||
# Если есть только левый потомок
|
||||
if root["left"] is None:
|
||||
return root["right"]
|
||||
# Если есть только правый потомок
|
||||
if root["right"] is None:
|
||||
return root["left"]
|
||||
if (root["left"] or root["right"]) is None:
|
||||
while current and current['left']:
|
||||
current = current['left']
|
||||
root["name"] = current["name"]
|
||||
root["phone"] = current["phone"]
|
||||
root["right"] = bst_delete(root["right"],current["name"])
|
||||
return root
|
||||
Loading…
Reference in New Issue
Block a user