您的位置:首页 > 理论基础 > 数据结构算法

pat 03-树2 List Leaves(mooc 陈越、何钦铭-数据结构)

2016-09-19 20:48 597 查看
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 NNN (≤10\le 10≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1N-1N−1. Then NNN 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.

  该题目是我在mooc上学习数据结构遇到的课后作业题,题目要求列出所有的叶子节点,并且顺序是从上到下,从左到右。其实就是一层一层的从左到右输出叶子节点。

输入:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出:
4 1 5

1.解法

  实际上就是一个层序遍历问题,在遍历过程中遇到叶子节点(两个儿子都是空)就输出该节点值。

from collections import deque #导入队列类deque
#将读入的数据转化为数字,遇到'-'时返回-1
def integer(a):
if a=='-':
return -1
else:
return int(a)

def build_tree():
n = input()
lists = []
for m in xrange(n):
line = raw_input().split() #读入一个节点
#因为raw_input()读入的类型为字符串,需要将其转换为整数,-1代表空。
 lists.append((integer(line[0]),integer(line[1]))) #储存一个节点
tag = [0 for m in xrange(n+1)] #tag[m]=0时说明该节点没有被其他节点指向,该节点为根节点。
for m in xrange(n):
tag[lists[m][0]] = 1
tag[lists[m][1]] = 1
#找出根节点
 for m in xrange(n):
if(tag[m]==0):
break
return (lists,m)

def find(lists,m): #找到所有的叶子节点
a = deque(maxlen=len(lists)+1) #申请一个比该树节点树略大的队列。
a.append(m) #
4000
层序遍历
result = []
while(len(a)):
m = a.popleft()
if(m==-1): #空节点
continue
if(lists[m][0]==-1 and lists[m][1]==-1): #叶子节点
result.append(m)
else:
a.append(lists[m][0]) #普通节点
a.append(lists[m][1])
result = [str(m) for m in result]
result = ' '.join(result) #返回结果字符串
return result

(lists,m) = build_tree()
print find(lists,m) #输出结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 python
相关文章推荐