1、树的层级遍历
- 时间复杂度:
O(n)
,其中n
为二叉树的节点个数。 - 空间复杂度:
O(n)
。
# 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 decorateRecord(self, root: Optional[TreeNode]) -> List[int]:
from collections import deque
ls_res = []
if not root:
return ls_res
queue = deque([root])
while queue:
for i in range(len(queue)):
node = queue.popleft()
ls_res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return ls_res
2、改写解法 1(使用两个队列)
# 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 decorateRecord(self, root: Optional[TreeNode]) -> List[int]:
from collections import deque
# jy: 存储遍历结果
ls_res = []
if not root:
return ls_res
# jy: 存储当前层节点
ls_cur = [root]
# jy: 当前层节点不为空时, 不断从当前层节点取数
while ls_cur:
# jy: 存储下一层节点, 遍历当前层节点时, 不断将下一层节点加入
ls_next = []
for node in ls_cur:
ls_res.append(node.val)
if node.left:
ls_next.append(node.left)
if node.right:
ls_next.append(node.right)
# jy: 当前层遍历结束后, 将下一层赋值给当前层, 继续下一轮循环
ls_cur = ls_next
return ls_res
参考自: