From d3c1d5a6ba52686dbef0515fa9741bc68fc13f6e Mon Sep 17 00:00:00 2001 From: terminaldweller Date: Sun, 19 Feb 2023 10:05:12 +0330 Subject: 103 --- 103/main.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 103/main.py diff --git a/103/main.py b/103/main.py new file mode 100644 index 0000000..2c18d85 --- /dev/null +++ b/103/main.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python + +from typing import Optional, List + + +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 [] + + res = [] + q = [root] + left_to_right = True + + while q: + level_size = len(q) + level = [] + + for i in range(level_size): + node = q.pop(0) + + if left_to_right: + level.append(node.val) + else: + level = [node.val] + level + + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + res.append(level) + left_to_right = not left_to_right + return res + + +if __name__ == "__main__": + solution = Solution() + print(solution.zigzagLevelOrder()) -- cgit v1.2.3