PHP前端开发

如何在Python中实现avl树运算

百变鹏仔 1天前 #Python
文章标签 如何在

Python执行avl树,代码详情:

import sys#创建树节点class TreeNode(object):def __init__(self,key):self.key=keyself.left=Noneself.right=Noneself.height=1class AVLTree(object):#插入节点def insert_node(self,root,key):#找到位置并插入节点if not root:return TreeNode(key)elif key<root.key: root.left="self.insert_node(root.left,key)" else: root.right="self.insert_node(root.right,key)" root.height="1+max(self.getHeight(root.left)," self.getheight balancefactor="self.getBalance(root)" if>1:if key<root.left.key: return self.rightrotate else: root.left="self.leftRotate(root.left)" if balancefactor key>root.right.key:return self.leftRotate(root)else:root.right=self.rightRotate(root.right)return self.leftRotate(root)return root#删除节点def delete_node(self,root,key):#找到要删除的节点并删除if not root:return rootelif key<root.key: root.left="self.delete_node(root.left,key)" elif key>root.key:root.right=self.delete_node(root.right,key)else:if root.left is None:temp=root.rightroot=Nonereturn tempelif root.right is None:temp=root.leftroot=Nonereturn temptemp=self.getMinValueNode(root.right)root.key=temp.keyroot.right=self.delete_node(root.right,temp.key)if root is None:return root#更新节点root.height=1+max(self.getHeight(root.left),self.getHeight(root.right))balanceFactor=self.getBalance(root)#平衡树if balanceFactor&gt;1:if self.getBalance(root.left)&gt;=0:return self.rightRotate(root)else:root.left=self.leftRotate(root.left)return self.rightRotate(root)if balanceFactor</root.key:></root.left.key:></root.key:>