7-2 先序序列创建二叉树,输出先序序列、中序序列、后序序列并输出叶子结点数 (10 分)对于给定的二叉树,输出其先序序列、中序序列、后序序列并输出叶子结点数。
输入格式:
二叉树的先序遍历序列。
提示:一棵二叉树的先序序列是一个字符串,若字符是‘#’,表示该二叉树是空树,否则该字符是相应结点的数据元素。
输出格式:
若是非空二叉树,则输出四行内容 第一行是二叉树的先序遍历序列; 第二行是二叉树的中序遍历序列; 第三行是二叉树的后序遍历序列; 第四行是叶子结点数;
若是空二叉树 只需输出叶子数0
输入样例1:
FCA##DB###EHM###G##
结尾无空行
输出样例1:
FCADBEHMG
ACBDFMHEG
ABDCMHGEF
4
结尾无空行
输入样例2:
结尾无空行
输出样例2:
0
结尾无空行
import sys
class BinNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinTree:
def __init__(self, data):
self.root = BinNode(data)
self.trail = []
self.countLeafNumber = 0
def preprint(self, r):
if r is None:
return
print(r.data, end="")
self.preprint(r.left)
self.preprint(r.right)
def midPrint(self, r):
if r is None:
return
self.midPrint(r.left)
print(r.data, end="")
self.midPrint(r.right)
def endPrint(self, r):
if r is None:
return
self.endPrint(r.left)
self.endPrint(r.right)
print(r.data, end="")
def findx(self, r, x):
if r.data == "#":
return "#"
if r.data == x:
self.trail.append(r.data)
return 1
found = self.findx(r.left, x)
if found != "#":
self.trail.append(r.data)
return 1
else:
foundRight = self.findx(r.right, x)
if foundRight != "#":
self.trail.append(r.data)
return 1
else:
return "#"
def countLeat(self, r):
if r is None:
return
if r.left is None and r.right is None:
self.countLeafNumber = self.countLeafNumber + 1
self.countLeat(r.left)
self.countLeat(r.right)
def add(r, x, i):
if x[i] != "#":
r.left = BinNode(x[i])
i = add(r.left, x, i + 1)
# 根据填的内容判定是否要继续深入
# 如果是#,则看看右边
# 不然则继续走
i = i + 1
if x[i] != "#":
r.right = BinNode(x[i])
i = add(r.right, x, i + 1)
return i
inputString = input()
if inputString[0] == "#":
print("0", end="")
sys.exit()
tree = BinTree(inputString[0])
add(tree.root, inputString, 1)
tree.preprint(tree.root)
print()
tree.midPrint(tree.root)
print()
tree.endPrint(tree.root)
print()
tree.countLeat(tree.root)
print(tree.countLeafNumber, end="")