LeetCode103 二叉树的锯齿形层序遍历
使用两个栈进行模拟 + 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 zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None: return []
ans, stack_odd, stack_even = [], [root], []
while stack_odd or stack_even:
if stack_odd:
odd_ans = []
while stack_odd:
cur = stack_odd.pop()
odd_ans.append(cur.val)
if cur.left: stack_even.append(cur.left)
if cur.right: stack_even.append(cur.right)
ans.append(odd_ans)
elif stack_even:
even_ans = []
while stack_even:
cur = stack_even.pop()
even_ans.append(cur.val)
if cur.right: stack_odd.append(cur.right)
if cur.left: stack_odd.append(cur.left)
ans.append(even_ans)
return ans