Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
- 时间限制:400ms
- 内存限制:64MB
- 代码长度限制:16kB
- 判题程序:系统默认
- 作者:陈越
- 单位:浙江大学
python3代码
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 5 15:01:41 2017
@author: Administrator
"""
from collections import deque
class node:
def __init__(self,ele):
self.left = None
self.right = None
self.element = ele
class Tree:
def __init__(self):
self.root = None
def buildtree(self,sum,llist,rlist):
treelist = []
for i in range(sum):
treelist.append(node(i))
for i in range(sum):
if llist[i] == "-" :
treelist[i].left = None
else:
l = int(llist[i])
treelist[i].left = treelist[l]
if rlist[i] == "-" :
treelist[i].right = None
else:
r = int(rlist[i])
treelist[i].right = treelist[r]
#find root node
tem = []
tem = rlist + llist
for seq in range(sum):
if str(seq) not in tem:
self.root = treelist[seq]
@staticmethod
def getResultList(node):
resultlist =[]
queue = deque([node,])
try:
while queue:
nodeout = queue.popleft()
if nodeout.left == None and nodeout.right == None:
resultlist.append(nodeout.element)
else:
if nodeout.left:
queue.append(nodeout.left)
if nodeout.right:
queue.append(nodeout.right)
finally:
return resultlist
def main():
rlist = []
llist = []
sum = int(input())
for x in range(sum):
strin = input().split()
llist.append(strin[0])
rlist.append(strin[1])
tree1 = Tree()
tree1.buildtree(sum,llist,rlist)
resultList=Tree().getResultList(tree1.root)
s = ""
for i in resultList:
s += str(i)+" "
s = s.strip()
print(s)
if __name__ == "__main__":
main()