Leetcode 102 二叉樹的層次遍歷 Python


二叉樹的層次遍歷

  

給定一個二叉樹,返回其按層次遍歷的節點值。 (即逐層地,從左到右訪問所有節點)。

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

    3
  / \
9 20
  / \
  15   7
返回其層次遍歷結果:
[
[3],
[9,20],
[15,7]
]

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if root == None:
            return []
        layer = [root]
        res = []
        while len(layer):
            this_res = []
            next_l = []
            for n in layer:
                this_res.append(n.val)
                if n.left:
                    next_l.append(n.left)
                if n.right:
                    next_l.append(n.right)
            res.append(this_res)
            layer = next_l
        return res

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM