前言

树型结构是一类重要的非线性数据结构,其中以树和二叉树最为常用,是以分支关系定义的层次结构。树结构在客观世界中广泛存在,如人类社会的族谱和各种社会组织机构;在计算机领域中也有广泛应用,如在编译程序中,可用树来表示源程序的语法结构;在数据库系统中,树型结构也是信息的重要组织形式之一;在机器学习中,决策树,随机森林,gbdt等是常见的树模型。

树(tree)是个结点的有限集。在任意一棵树中:(1)有且仅有一个特定的称为根(root)的节点;(2)当时,其余节点可分为个互不相交的有限集其中每一个集合本身又是一棵树,并且称为根的子树(subtree)。

图1 树型结构

python创建与遍历二叉树

python创建和遍历二叉树,可以使用递归的方式,源代码如下:

#!/usr/bin/python 
class node():
	def __init__(self,k=none,l=none,r=none):
		self.key=k;
		self.left=l;
		self.right=r;
 
def create(root):
	a=raw_input('enter a key:');
	if a is '#':
		root=none;
	else:
		root=node(k=a);
		root.left=create(root.left);
		root.right=create(root.right);
	return root;
 
def preorder(root):  #前序遍历
	if root is none:
		return ;
	else :
		print root.key;
		preorder(root.left);
		preorder(root.right);
 
def inorder(root):  #中序遍历
	if root is none:
		return ;
	else:
		inorder(root.left);
		print root.key;
		inorder(root.right);
 
def postorder(root): # 后序遍历
	if root is none:
		return ;
	else :
		postorder(root.left);
		postorder(root.right);
		print root.key;
		
root=none;  # 测试代码
root=create(root);
preorder(root);
inorder(root);
postorder(root);
 

运行程序,建立二叉树如图:

前序遍历结果为: a  b  c  d  e  f

中序遍历结果为:c  b  d  a  f  e 

后序遍历结果为:c  d  b  f  e  a 

总结

到此这篇关于python创建与遍历二叉树的文章就介绍到这了,更多相关python创建与遍历二叉树内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!