Skip to content

Latest commit

 

History

History
56 lines (49 loc) · 1.37 KB

102. 二叉树的层序遍历 - Medium.md

File metadata and controls

56 lines (49 loc) · 1.37 KB
  • 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行
  • 例如:
    • 给定二叉树: [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

Solution

  • 层次遍历:使用栈保存每一层的节点
  • 在每一层中单独设置一个list保存
  • 注意None节点的判断
# 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:
            return []
        else:
            ans, stack = [], [root]
            while stack:
                layer_node, layer_val = [], []
                while stack:
                    current = stack.pop(0)
                    layer_val.append(current.val)

                    if current.left:
                        layer_node.append(current.left)
                    if current.right:
                        layer_node.append(current.right)
                
                stack.extend(layer_node)
                ans.append(layer_val)
            
            return ans