題目
Sort binary tree by levels
You are given a binary tree:
class Node:
def __init__(self, L, R, n):
self.left = L
self.right = R
self.value = n
Your task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on.
Return empty list if root is None.
Example 1 - following tree:
2
8 9
1 3 4 5
Should return following list:
[2,8,9,1,3,4,5]
Example 2 - following tree:
1
8 4
3 5
7
Should return following list:
[1,8,4,3,5,7]
笨蛋解法
想了大半天,終于做出來了?。?!
不過也看了提示,有人說用隊(duì)列,于是我用了隊(duì)列嗯!
有些啰嗦的笨蛋解法,不過用評(píng)論里大神的話來說,確實(shí)就是簡(jiǎn)單的遍歷啊!
import queue
class Node:
def __init__(self, L, R, n):
self.left = L
self.right = R
self.value = n
def tree_by_levels(node):
if node==None:
return []
else:
res = []
a = queue.Queue()
a.put(node)
while(a.empty()==False):
b = a.get()
res.append(b.value)
if isinstance(b.left, Node):
a.put(b.left)
elif b.left!=None:
res.append(b.left)
if isinstance(b.right, Node):
a.put(b.right)
elif b.right!=None:
res.append(b.right)
return res
大神の解
嗯,用list也不錯(cuò)啊,看了其他用queue和deque的解,思路一樣的,寫的比我的破爛解簡(jiǎn)潔優(yōu)美多了
def tree_by_levels(node):
p, q = [], [node]
while q:
v = q.pop(0)
if v is not None:
p.append(v.value)
q += [v.left,v.right]
return p if not node is None else []