1. 程式人生 > >leetcode 107 二叉樹的層次遍歷2 ----python3

leetcode 107 二叉樹的層次遍歷2 ----python3

給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)

例如: 給定二叉樹 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的層次遍歷為:

[
  [15,7],
  [9,20],
  [3]
]
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from queue import Queue
class Solution:

    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        l = []
        q = Queue()
        if root != None:
            q.put(root)
        while not q.empty():
            tmp = []
            node = q.get()
            for i in range(0,q.qsize()):
                tmp.append(node.val)
                if node.left:
                    q.put(node.left)
                if node.right:
                    q.put(node.right)
            l.append(tmp)
        return l