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

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) #层序遍历
  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)  #输出结果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值