diff options
author | terminaldweller <thabogre@gmail.com> | 2023-02-19 06:35:12 +0000 |
---|---|---|
committer | terminaldweller <thabogre@gmail.com> | 2023-02-19 06:35:12 +0000 |
commit | d3c1d5a6ba52686dbef0515fa9741bc68fc13f6e (patch) | |
tree | 3a7616a7f4fe6e0288e39128bb5961fd60cab7e3 /103 | |
parent | 226 (diff) | |
download | leetcode-d3c1d5a6ba52686dbef0515fa9741bc68fc13f6e.tar.gz leetcode-d3c1d5a6ba52686dbef0515fa9741bc68fc13f6e.zip |
103
Diffstat (limited to '103')
-rw-r--r-- | 103/main.py | 45 |
1 files changed, 45 insertions, 0 deletions
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()) |