题目:
二叉树的层序遍历:给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
思路:
层序遍历的常用解题思路。
程序:
# 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 [] result = [] current_level = [root] while current_level: auxiliary = [] next_level = [] for node in current_level: auxiliary.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) result.append(auxiliary) current_level = next_level return result