December 5, 2024
I am glad I was able to make a solution from my own intuition.
1from collections import deque2# Definition for a binary tree node.3# class TreeNode:4# def __init__(self, val=0, left=None, right=None):5# self.val = val6# self.left = left7# self.right = right8class Solution:9 def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:10 nodes = deque([root] if root else [])11 rightToLeft = False1213 result = []14 while nodes:15 level = []16 children = deque([])17 for i in range(len(nodes)):18 if rightToLeft:19 node = nodes.pop()20 node.right and children.appendleft(node.right)21 node.left and children.appendleft(node.left)22 else:23 node = nodes.popleft()24 node.left and children.append(node.left)25 node.right and children.append(node.right)26 level.append(node.val)27 result.append(level)28 if rightToLeft:29 nodes += children30 else:31 nodes = children + nodes32 rightToLeft = not rightToLeft33 return result
Time complexity is O(n) = n and space complexity is O(n).
LeetCode 236. Lowest Common Ancestor of a Binary Tree