每日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]

笨蛋解法

想了大半天,终于做出来了!!!
不过也看了提示,有人说用队列,于是我用了队列嗯!
有些啰嗦的笨蛋解法,不过用评论里大神的话来说,确实就是简单的遍历啊!

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也不错啊,看了其他用queue和deque的解,思路一样的,写的比我的破烂解简洁优美多了

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 []
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容