二叉树(python)

mac2022-06-30  134

import queue class Node(object): def __init__(self,elem): self.elem=elem self.left=None self.right=None class tree(object): def __init__(self): self.root=None def add(self,item): node=Node(item) if self.root is None: self.root=node else: queue=[self.root] while queue: cur_root=queue.pop(0) if cur_root.left is None: cur_root.left=node return else: queue.append(cur_root.left) if cur_root.right is None: cur_root.right=node return else: queue.append(cur_root.right) def trave(self): if self.root is None: return else: queue=[self.root] while queue: cur_root=queue.pop(0) print(cur_root.elem,end=" ") if cur_root.left is not None: queue.append(cur_root.left) if cur_root.right is not None: queue.append(cur_root.right) def preorder(self, node): """先序遍历""" if node is None: return cur_root=node print(cur_root.elem,end=" ") self.preorder(cur_root.left) self.preorder(cur_root.right) def inorder(self, node): """中序遍历""" if node is None: return cur_root=node self.inorder(cur_root.left) print(cur_root.elem,end=" ") self.inorder(cur_root.right) def postorder(self, node): """后序遍历""" if node is None: return cur_root=node self.postorder(cur_root.left) self.postorder(cur_root.right) print(cur_root.elem,end=" ") if __name__ == '__main__': 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.trave() print(" ") tree.preorder(tree.root) print(" ") tree.inorder(tree.root) print(" ") tree.postorder(tree.root)

 

最新回复(0)