每日kata~13~Sort binary tree by levels

題目

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 []
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容