# -*- coding:utf-8 -*- class Node(object): def __init__(self,index,left=None,right=None,parent=None): self.index=index self.left_child=left self.right_child=right self.parent=parent class BinaryTree(object): def __init__(self): self.root=None def insert(self,node): n=self.root if n==None: self.root=node return while True: if node.index<=n.index: if n.left_child==None: node.parent=n n.left_child=node break else: n=n.left_child if node.index>n.index: if n.right_child==None: node.parent=n n.right_child=node break else: n=n.right_child def pre_pravel(self,node): print(node.index) if node.left_child!=None: self.pre_pravel(node.left_child) if node.right_child!=None: self.pre_pravel(node.right_child) tree=BinaryTree() node_dict={} for i in range(1,10): node_dict[i]=Node(i) tree.insert(node_dict[i]) tree.pre_pravel(tree.root)
Python实现二叉树
最新推荐文章于 2022-11-02 18:42:56 发布