二叉树的创建以及四种遍历,叶子结点的数量,二叉树深度(简单二叉树)

本文详细介绍了二叉树的前序、中序、后序及层次遍历算法,并提供了Python实现代码。此外还讲解了如何计算二叉树的深度和叶子节点数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前序遍历:DLR

中序遍历:LDR

后序遍历:LRD

这三种遍历都采用递归的形式


层次遍历:从上到下,从左到右依次遍历

这种遍历采用队列的形式


叶子结点的数量:就是判断有多少度为0的结点

树的深度:判断一共有多少层

#!/usr/bin/python
#coding: utf-8

class Tree_Node(object):

	def __init__(self, val = "#"):
		self.val = val
		self.left_root = None
		self.right_root = None

class Tree(object):

	def __init__(self, h):
		# h 变量用来查看树的深度
		self.h = 1

	def Create_Node(self, root):
		u"创建二叉树"
		val = raw_input("->")
		if val == "#":
			root = None
		else:
			root.val = val
			root.left_root = Tree_Node()
			self.Create_Node(root.left_root)
			root.right_root = Tree_Node()
			self.Create_Node(root.right_root)

	def Pre_Order(self, root):
		u"前序遍历"
		if root is not None:
			if root.val == "#":
				return
			else:
				print root.val,
				self.Pre_Order(root.left_root)
				self.Pre_Order(root.right_root)

	def In_Order(self, root):
		u"中序遍历"
		if root is not None:
			if root.val == "#":
				return
			else:
				self.In_Order(root.left_root)
				print root.val,
				self.In_Order(root.right_root)

	def Post_Order(self, root):
		u"后序遍历"
		if root is not None:
			if root.val == '#':
				return
			else:
				self.Post_Order(root.left_root)
				self.Post_Order(root.right_root)
				print root.val,

	def Level_Order(self, root):
		u"层次遍历"
		if root is not None:
			que = [root]
			while len(que) > 0:
				tree = que.pop(0)
				if tree.val != "#":
					print tree.val,
					que.append(tree.left_root)
					que.append(tree.right_root)

	def Tree_Left(self, root):
		u"叶子结点的数量"
		left = 0
		if root.val is not None and root.val != "#":
			if root.left_root.val == "#" and root.right_root.val == "#":
				left = 1
			else:
				left = self.Tree_Left(root.left_root) + self.Tree_Left(root.right_root)

		return left

	def Tree_Depth(self, root, depth):
		u"树的深度"
		if root is None or root.val == "#":
			return
		if root is not None and root.val != "#":
			if self.h < depth:
				self.h = depth
			self.Tree_Depth(root.left_root, depth + 1)
			self.Tree_Depth(root.right_root, depth + 1)

if __name__ == "__main__":

	tn = Tree_Node()
	a = Tree(0)
	a.Create_Node(tn)

	print a.Pre_Order.__doc__,
	a.Pre_Order(tn)
	print 

	print a.In_Order.__doc__,
	a.In_Order(tn)
	print

	print a.Post_Order.__doc__,
	a.Post_Order(tn)
	print

	print a.Level_Order.__doc__,
	a.Level_Order(tn)
	print

	print a.Tree_Left.__doc__,
	print a.Tree_Left(tn)

	print a.Tree_Depth.__doc__,
	a.Tree_Depth(tn, 1)
	print a.h


输入样例


输出样例


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值