LeetCode-102二叉木の階層遍歴---Pythonコード実現と詳細解

1519 ワード

タイトル:
ツリーを指定して、階層的にループするノード値を返します.(つまり、左から右へすべてのノードに階層的にアクセスします).
例:
与えられた二叉木:[3,9,20,null,null,15,7],
     3
   /   \
9       20
         / \
      5      7
階層遍歴の結果を返します.
[
[3],
[9,20],
[15,7]
]
 
考え方:
ルートノード3にアクセスする場合はその左右の子供ノード[9,20]を先に保存し、[9,20]にアクセスしてその2つのノードの左右の子供ノードを[null,null,15,7]に保存し、[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 not root:                 # root       []
            return []
        res = []                     #        
        cur_nodes = [root]           #      
        next_nodes = []              #         
        res.append([i.val for i in cur_nodes])     #          res 
        while cur_nodes or next_nodes:    #              
            for node in cur_nodes:        #             next_nodes
                if node.left:
                    next_nodes.append(node.left)
                if node.right:
                    next_nodes.append(node.right)
            if next_nodes:                #            res
                res.append(
                    [i.val for i in next_nodes]
                )
            cur_nodes = next_nodes  #        next_nodes
            next_nodes = []  #        
        return res