R2-树与二叉树篇
层序遍历+双端队列deque
# 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 zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:#层序遍历+双端队列if not root:return []ret=[]#[root]应该代表root根节点#存储树的双端队列只需要popleft即可,然后tmp根据层数的奇偶性来appendleft()还是append()deque=collections.deque([root])while deque:tmp=collections.deque()for _ in range(len(deque)):node=deque.popleft()if len(ret)%2==0:#奇数层->队尾tmp.append(node.val)else:#偶数层->队列头部tmp.appendleft(node.val)#子树入队列if node.left:deque.append(node.left)if node.right:deque.append(node.right)ret.append(list(tmp))return ret
ps:
k神
另外两种方法:方法三:层序遍历 + 倒序,方法二:层序遍历 + 双端队列(奇偶层逻辑分离)