1. 程式人生 > >pat 03-樹2 List Leaves(mooc 陳越、何欽銘-資料結構)

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)  #輸出結果