From 6925c6815f6fe48b39a0538cdf03cef3bb6c7805 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Tue, 26 Apr 2022 00:21:37 +0530 Subject: [PATCH] btree-level-order-traversal py3 --- .../README.md | 28 +++++++++++ .../python3/solution.py | 49 +++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 0102_binary-tree-level-order-traversal/README.md create mode 100644 0102_binary-tree-level-order-traversal/python3/solution.py diff --git a/0102_binary-tree-level-order-traversal/README.md b/0102_binary-tree-level-order-traversal/README.md new file mode 100644 index 0000000..90a768d --- /dev/null +++ b/0102_binary-tree-level-order-traversal/README.md @@ -0,0 +1,28 @@ +Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) + + Input: root = [3,9,20,null,null,15,7] + Output: [[3],[9,20],[15,7]] + + +**Example 2:** + + Input: root = [1] + Output: [[1]] + + +**Example 3:** + + Input: root = [] + Output: [] + + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 2000]`. +* `-1000 <= Node.val <= 1000` + +https://leetcode.com/problems/binary-tree-level-order-traversal/ \ No newline at end of file diff --git a/0102_binary-tree-level-order-traversal/python3/solution.py b/0102_binary-tree-level-order-traversal/python3/solution.py new file mode 100644 index 0000000..6efe0fe --- /dev/null +++ b/0102_binary-tree-level-order-traversal/python3/solution.py @@ -0,0 +1,49 @@ +# 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 + +from collections import deque + +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + ''' + BFS + ''' + + if root is None: return [] + + q = deque([root]) + results = [] + + while q: + n = len(q) + + level = [] + # Idea here is we iterate through the queue, the queue + # will always contain 1, 2, 4, 8 ... elements for each + # level since we'll be appending None .left/.right nodes + # also. This makes it easier to do the computation. + for i in range(n): + curr = q.popleft() + + # Could be None, ignore if that's the case + if curr: + level.append(curr.val) + + # It's okay to append None values here, the condition + # above will filter it out + q.append(curr.left) + q.append(curr.right) + + # Since there's a chance that at the last level of the tree, we + # might be pushing None nodes due to .left/.right being None, we + # might have an empty level. We check and avoid adding the empty + # level in this case. + if level: + results.append(level) + + return results + \ No newline at end of file