二叉树
class Node(object): def __init__(self,val,lchild=None,rchild=None): self.val=val self.lchild=lchild self.rchild=rchild class Tree(object): def __init__(self): self.root=None def add(self,item): node=Node(item) if self.root==None: self.root=node return queue=[self.root] while queue: cur_node=queue.pop(0) if cur_node.lchild==None: cur_node.lchild=node return else: queue.append(cur_node.lchild) if cur_node.rchild==None: cur_node.rchild=node return else: queue.append(cur_node.rchild) def breadth_travel(self): if self.root==None: print('NULL') return queue=[self.root] while queue: cur_node = queue.pop(0) print(cur_node.val, end=' ') if cur_node.lchild!=None: queue.append(cur_node.lchild) if cur_node.rchild!=None: queue.append(cur_node.rchild) def preorder_travel(self,node): if node==None: return print(node.val,end=' ') self.preorder_travel(node.lchild) self.preorder_travel(node.rchild) def inorder_travel(self,node): if node==None: return self.inorder_travel(node.lchild) print(node.val, end=' ') self.inorder_travel(node.rchild) def postorder_travel(self,node): if node==None: return self.postorder_travel(node.lchild) self.postorder_travel(node.rchild) print(node.val, end=' ') tree=Tree() tree.add(0) tree.add(1) tree.add(2) tree.add(3) tree.add(4) tree.add(5) tree.add(6) tree.add(7) tree.add(8) tree.add(9) tree.breadth_travel() print(' ') tree.preorder_travel(tree.root) print(' ') tree.inorder_travel(tree.root) print(' ') tree.postorder_travel(tree.root)
标签:node,None,06,cur,Python,self,tree,算法,travel From: https://www.cnblogs.com/yyyjw/p/18004943