Skip to content

Commit bf2d188

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.8 MB (5.01%)
1 parent 70a019f commit bf2d188

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>Given the <code>root</code> of a binary tree, return <em><strong>the vertical order traversal</strong> of its nodes&#39; values</em>. (i.e., from top to bottom, column by column).</p>
2+
3+
<p>If two nodes are in the same row and column, the order should be from <strong>left to right</strong>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
<img alt="" src="https://assets.leetcode.com/uploads/2024/09/23/image1.png" style="width: 400px; height: 273px;" />
8+
<pre>
9+
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
10+
<strong>Output:</strong> [[9],[3,15],[20],[7]]
11+
</pre>
12+
13+
<p><strong class="example">Example 2:</strong></p>
14+
<img alt="" src="https://assets.leetcode.com/uploads/2024/09/23/image3.png" style="width: 450px; height: 285px;" />
15+
<pre>
16+
<strong>Input:</strong> root = [3,9,8,4,0,1,7]
17+
<strong>Output:</strong> [[4],[9],[3,0,1],[8],[7]]
18+
</pre>
19+
20+
<p><strong class="example">Example 3:</strong></p>
21+
<img alt="" src="https://assets.leetcode.com/uploads/2024/09/23/image2.png" style="width: 350px; height: 342px;" />
22+
<pre>
23+
<strong>Input:</strong> root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
24+
<strong>Output:</strong> [[4],[2,5],[1,10,9,6],[3],[11]]
25+
</pre>
26+
27+
<p>&nbsp;</p>
28+
<p><strong>Constraints:</strong></p>
29+
30+
<ul>
31+
<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>
32+
<li><code>-100 &lt;= Node.val &lt;= 100</code></li>
33+
</ul>
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Approach 2: BFS without sorting
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
# Definition for a binary tree node.
7+
# class TreeNode:
8+
# def __init__(self, val=0, left=None, right=None):
9+
# self.val = val
10+
# self.left = left
11+
# self.right = right
12+
13+
from collections import defaultdict, deque
14+
15+
class Solution:
16+
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
17+
if not root:
18+
return []
19+
20+
columnTable = defaultdict(list)
21+
min_column = max_column = 0
22+
queue = deque([(root, 0)])
23+
24+
while queue:
25+
node, column = queue.popleft()
26+
27+
if node is not None:
28+
columnTable[column].append(node.val)
29+
min_column = min(min_column, column)
30+
max_column = max(max_column, column)
31+
32+
queue.append([node.left, column - 1])
33+
queue.append([node.right, column + 1])
34+
35+
return [columnTable[x] for x in range(min_column, max_column + 1)]
36+

0 commit comments

Comments
 (0)