问题
给定二叉树,返回其节点值的水平阶遍历。(即,从左到右,逐级)。
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1] 输出:[[1]]
示例 3:
输入:root = [] 输出: []
约束:
- 树中的节点数在 范围内。
[0, 2000]
-1000 <= Node.val <= 1000
解决方案
使用递归:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
if not root:
return levels
def helper(node, level):
# start the current level
if len(levels) == level:
levels.append([])
# append the current node value
levels[level].append(node.val)
# process child nodes for the next level
if node.left:
helper(node.left, level + 1)
if node.right:
helper(node.right, level + 1)
helper(root, 0)
return levels
这有点令人困惑,我不喜欢它,我也没有想出它。我更喜欢带有队列的 BFS 方法。
BFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
res = []
# queue
q = collections.deque()
q.append(root)
while q:
# while queue is non-empt
qLen = len(q)
# loop through all values in the queue
# makes sure we iterate one level at a time
level = []
# for all nodes in that level
for i in range(qLen):
node = q.popleft()
# FIFO by popping left
if node:
level.append(node.val)
# technically these could be null, hence the if node above
q.append(node.left)
q.append(node.right)
if level:
res.append(level)
return res