文章目录
- 一. 二叉树基本概念
- 二. 二叉树的性质
- 三. 二叉树的代码实现
- 四. 二叉树的先序、中序、后序遍历
一. 二叉树基本概念
二. 二叉树的性质
三. 二叉树的代码实现
class Node(object):"""二叉树节点"""def __init__(self,item):self.elem = itemself.lchild = Noneself.rchild = Noneclass Tree(object):"""二叉树"""def __init__(self):self.root = Nonedef add(self,item):node = Node(item)if self.root is None:self.root = nodereturnqueue = [self.root]while queue:cur_node = queue.pop(0)if cur_node.lchild is None:cur_node.lchild = nodereturnelse:queue.append(cur_node.lchild)if cur_node.rchild is None:cur_node.rchild = nodereturnelse:queue.append(cur_node.rchild)def breadth_travel(self):"""广度遍历"""if self.root is None:returnqueue = [self.root]while queue:cur_node = queue.pop(0)print(cur_node.elem)if cur_node.lchild is not None:queue.append(cur_node.lchild)if cur_node.rchild is not None:queue.append(cur_node.rchild)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.breadth_travel()
四. 二叉树的先序、中序、后序遍历
class Node(object):"""二叉树节点"""def __init__(self,item):self.elem = itemself.lchild = Noneself.rchild = Noneclass Tree(object):"""二叉树"""def __init__(self):self.root = Nonedef add(self,item):node = Node(item)if self.root is None:self.root = nodereturnqueue = [self.root]while queue:cur_node = queue.pop(0)if cur_node.lchild is None:cur_node.lchild = nodereturnelse:queue.append(cur_node.lchild)if cur_node.rchild is None:cur_node.rchild = nodereturnelse:queue.append(cur_node.rchild)def breadth_travel(self):"""广度遍历"""if self.root is None:returnqueue = [self.root]while queue:cur_node = queue.pop(0)print(cur_node.elem)if cur_node.lchild is not None:queue.append(cur_node.lchild)if cur_node.rchild is not None:queue.append(cur_node.rchild)def preorder(self,node):"""先序遍历"""if node is None:returnprint(node.elem,end=" ")self.preorder(node.lchild)self.preorder(node.rchild)def inorder(self,node):"""中序遍历"""if node is None:returnself.inorder(node.lchild)print(node.elem,end=" ")self.inorder(node.rchild)def postorder(self,node):"""后序遍历"""if node is None:returnself.postorder(node.lchild)self.postorder(node.rchild)print(node.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.breadth_travel()# print(" ")tree.preorder(tree.root)print(" ")tree.inorder(tree.root)print(" ")tree.postorder(tree.root)print(" ")