题目
输入一棵二叉树,请按从上到下、从左到右的顺序输出二叉树各结点的值。要求:二叉树用二叉链表存储。 输入中,每个结点的左括号和右括号之间没有空格,相邻结点之间用一个空格分开。最后输入的括号()表示结束。如果从根到叶结点的路径上有的结点漏输或多输,则输出-1。
输入示例:
以上输入序列为:
(3,L) (2,LR) (4,) (1,R) ()
输出为:
4 3 1 2
解决方法:
- 如图创建链式结构
class TreeNode():
def __init__(self,val):
self.val = val
self.left = None
self.right = None
- 创建二叉树(这个是我写这篇文章的原因,希望给别人一点参考,因为输入格式,我找了很多发现都没有这种格式的创建形式,只能自己写了)
# 将输入格式为(3,L) (2,LR) (4,) (1,R) ()的转为2个列表
n = input().split(" ")
nums = []
paths = []
for data in n:
# 当遇到()为结束
if data != '()':
num,path = data.split(",")
# 去掉左右2个括号
nums.append(int(num.lstrip("(")))
paths.append(path.rstrip(")"))
# 初始化
root = TreeNode(-1)
for i in range(len(nums)):
# path为空为root
if paths[i] == '':
root.val = nums[i]
else:
# 创建一个临时指针用来遍历
node = root
for j in list(paths[i]):
if j == 'L':
# j为L表示要往左侧走,检查左侧是否为None,当为None时,创建一个结点,-1为题目要求,可按你自己的题目要求改
if node.left == None:
node.left = TreeNode(-1)
node = node.left
else:
node = node.left
elif j == 'R':
if node.right == None:
node.right = TreeNode(-1)
node = node.right
else:
node = node.right
# 结束,赋值
node.val = nums[i]
- 层次遍历(没啥新意,就是传入头节点,然后用一个队列辅助)
def levelPrint(root):
if not root:
return []
current = [root]
outList= []
while current:
next = []
for point in current:
if point.left:
next.append(point.left)
if point.right:
next.append(point.right)
if point.val != -1:
outList.append(point.val)
current = next
return outList
完整代码
class TreeNode():
def __init__(self,val):
self.val = val
self.left = None
self.right = None
def levelPrint(root):
if not root:
return []
current = [root]
outList= []
while current:
next = []
for point in current:
if point.left:
next.append(point.left)
if point.right:
next.append(point.right)
if point.val != -1:
outList.append(point.val)
current = next
return outList
# 将输入格式为(3,L) (2,LR) (4,) (1,R) ()的转为2个列表
n = input().split(" ")
nums = []
paths = []
for data in n:
# 当遇到()为结束
if data != '()':
num,path = data.split(",")
# 去掉左右2个括号
nums.append(int(num.lstrip("(")))
paths.append(path.rstrip(")"))
# 初始化
root = TreeNode(-1)
for i in range(len(nums)):
# path为空为root
if paths[i] == '':
root.val = nums[i]
else:
# 创建一个临时指针用来遍历
node = root
for j in list(paths[i]):
if j == 'L':
# j为L表示要往左侧走,检查左侧是否为None,当为None时,创建一个结点,-1为题目要求,可按你自己的题目要求改
if node.left == None:
node.left = TreeNode(-1)
node = node.left
else:
node = node.left
elif j == 'R':
if node.right == None:
node.right = TreeNode(-1)
node = node.right
else:
node = node.right
# 结束,赋值
node.val = nums[i]
l = levelPrint(root)
for i in l:
print(i,end=" ")