📅  最后修改于: 2023-12-03 14:49:01.603000             🧑  作者: Mango
二叉树的顺时针螺旋遍历是一种将二叉树节点按照顺时针螺旋的顺序遍历的方法。这种遍历方式可以用于打印二叉树节点的路径或者寻找最优路径等问题。
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
from collections import deque
class Solution:
def spiralOrder(self, root: TreeNode) -> List[int]:
if not root:
return []
queue = deque()
queue.append(root)
is_reverse = False
res = []
while queue:
size = len(queue)
level_nodes = []
for i in range(size):
node = queue.popleft()
level_nodes.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if is_reverse:
level_nodes.reverse()
res += level_nodes
is_reverse = not is_reverse
return res