Skip to content

Commit d360347

Browse files
committed
feat: add solutions to lc problem: No.0314
No.0314.Binary Tree Vertical Order Traversal
1 parent 4280847 commit d360347

File tree

6 files changed

+697
-87
lines changed

6 files changed

+697
-87
lines changed

solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README.md

Lines changed: 278 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,17 @@
4646

4747
<!-- 这里可写通用的实现逻辑 -->
4848

49-
“BFS 层次遍历”实现。
49+
**方法一:DFS**
50+
51+
DFS 遍历二叉树,记录每个节点的值、深度,以及横向的偏移量。然后对所有节点按照横向偏移量从小到大排序,再按照深度从小到大排序,最后按照横向偏移量分组。
52+
53+
时间复杂度 $O(n\log \log n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。
54+
55+
**方法二:BFS**
56+
57+
本题较好的做法应该是 BFS,从上往下逐层进行遍历。
58+
59+
时间复杂度 $O(n\log n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的结点数。
5060

5161
<!-- tabs:start -->
5262

@@ -62,22 +72,45 @@
6272
# self.left = left
6373
# self.right = right
6474
class Solution:
65-
def verticalOrder(self, root: TreeNode) -> List[List[int]]:
75+
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
76+
def dfs(root, depth, offset):
77+
if root is None:
78+
return
79+
d[offset].append((depth, root.val))
80+
dfs(root.left, depth + 1, offset - 1)
81+
dfs(root.right, depth + 1, offset + 1)
82+
83+
d = defaultdict(list)
84+
dfs(root, 0, 0)
85+
ans = []
86+
for _, v in sorted(d.items()):
87+
v.sort(key=lambda x: x[0])
88+
ans.append([x[1] for x in v])
89+
return ans
90+
```
91+
92+
```python
93+
# Definition for a binary tree node.
94+
# class TreeNode:
95+
# def __init__(self, val=0, left=None, right=None):
96+
# self.val = val
97+
# self.left = left
98+
# self.right = right
99+
class Solution:
100+
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
66101
if root is None:
67102
return []
68103
q = deque([(root, 0)])
69-
offset_vals = defaultdict(list)
104+
d = defaultdict(list)
70105
while q:
71-
node, offset = q.popleft()
72-
offset_vals[offset].append(node.val)
73-
if node.left:
74-
q.append((node.left, offset - 1))
75-
if node.right:
76-
q.append((node.right, offset + 1))
77-
res = []
78-
for _, vals in sorted(offset_vals.items(), key=lambda x: x[0]):
79-
res.append(vals)
80-
return res
106+
for _ in range(len(q)):
107+
root, offset = q.popleft()
108+
d[offset].append(root.val)
109+
if root.left:
110+
q.append((root.left, offset - 1))
111+
if root.right:
112+
q.append((root.right, offset + 1))
113+
return [v for _, v in sorted(d.items())]
81114
```
82115

83116
### **Java**
@@ -101,31 +134,247 @@ class Solution:
101134
* }
102135
*/
103136
class Solution {
137+
private TreeMap<Integer, List<int[]>> d = new TreeMap<>();
138+
104139
public List<List<Integer>> verticalOrder(TreeNode root) {
140+
dfs(root, 0, 0);
141+
List<List<Integer>> ans = new ArrayList<>();
142+
for (var v : d.values()) {
143+
Collections.sort(v, (a, b) -> a[0] - b[0]);
144+
List<Integer> t = new ArrayList<>();
145+
for (var e : v) {
146+
t.add(e[1]);
147+
}
148+
ans.add(t);
149+
}
150+
return ans;
151+
}
152+
153+
private void dfs(TreeNode root, int depth, int offset) {
105154
if (root == null) {
106-
return Collections.emptyList();
155+
return;
107156
}
108-
Map<Integer, List<Integer>> offsetVals = new TreeMap<>();
109-
Map<TreeNode, Integer> nodeOffsets = new HashMap<>();
110-
Deque<TreeNode> q = new ArrayDeque<>();
111-
q.offer(root);
112-
nodeOffsets.put(root, 0);
157+
d.computeIfAbsent(offset, k -> new ArrayList<>()).add(new int[] {depth, root.val});
158+
dfs(root.left, depth + 1, offset - 1);
159+
dfs(root.right, depth + 1, offset + 1);
160+
}
161+
}
162+
```
113163

164+
```java
165+
/**
166+
* Definition for a binary tree node.
167+
* public class TreeNode {
168+
* int val;
169+
* TreeNode left;
170+
* TreeNode right;
171+
* TreeNode() {}
172+
* TreeNode(int val) { this.val = val; }
173+
* TreeNode(int val, TreeNode left, TreeNode right) {
174+
* this.val = val;
175+
* this.left = left;
176+
* this.right = right;
177+
* }
178+
* }
179+
*/
180+
class Solution {
181+
public List<List<Integer>> verticalOrder(TreeNode root) {
182+
List<List<Integer>> ans = new ArrayList<>();
183+
if (root == null) {
184+
return ans;
185+
}
186+
Deque<Pair<TreeNode, Integer>> q = new ArrayDeque<>();
187+
q.offer(new Pair<>(root, 0));
188+
TreeMap<Integer, List<Integer>> d = new TreeMap<>();
114189
while (!q.isEmpty()) {
115-
TreeNode node = q.poll();
116-
int offset = nodeOffsets.get(node);
117-
offsetVals.computeIfAbsent(offset, k -> new ArrayList<>()).add(node.val);
118-
if (node.left != null) {
119-
q.offer(node.left);
120-
nodeOffsets.put(node.left, offset - 1);
190+
for (int n = q.size(); n > 0; --n) {
191+
var p = q.pollFirst();
192+
root = p.getKey();
193+
int offset = p.getValue();
194+
d.computeIfAbsent(offset, k -> new ArrayList()).add(root.val);
195+
if (root.left != null) {
196+
q.offer(new Pair<>(root.left, offset - 1));
197+
}
198+
if (root.right != null) {
199+
q.offer(new Pair<>(root.right, offset + 1));
200+
}
121201
}
122-
if (node.right != null) {
123-
q.offer(node.right);
124-
nodeOffsets.put(node.right, offset + 1);
202+
}
203+
return new ArrayList<>(d.values());
204+
}
205+
}
206+
```
207+
208+
### **C++**
209+
210+
```cpp
211+
/**
212+
* Definition for a binary tree node.
213+
* struct TreeNode {
214+
* int val;
215+
* TreeNode *left;
216+
* TreeNode *right;
217+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
218+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
219+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
220+
* };
221+
*/
222+
using pii = pair<int, int>;
223+
224+
class Solution {
225+
public:
226+
map<int, vector<pii>> d;
227+
228+
vector<vector<int>> verticalOrder(TreeNode* root) {
229+
dfs(root, 0, 0);
230+
vector<vector<int>> ans;
231+
for (auto& [_, v] : d) {
232+
sort(v.begin(), v.end(), [&](pii& a, pii& b) {
233+
return a.first < b.first;
234+
});
235+
vector<int> t;
236+
for (auto& x : v) {
237+
t.push_back(x.second);
125238
}
239+
ans.push_back(t);
126240
}
127-
return new ArrayList<>(offsetVals.values());
241+
return ans;
128242
}
243+
244+
void dfs(TreeNode* root, int depth, int offset) {
245+
if (!root) return;
246+
d[offset].push_back({depth, root->val});
247+
dfs(root->left, depth + 1, offset - 1);
248+
dfs(root->right, depth + 1, offset + 1);
249+
}
250+
};
251+
```
252+
253+
```cpp
254+
/**
255+
* Definition for a binary tree node.
256+
* struct TreeNode {
257+
* int val;
258+
* TreeNode *left;
259+
* TreeNode *right;
260+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
261+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
262+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
263+
* };
264+
*/
265+
class Solution {
266+
public:
267+
vector<vector<int>> verticalOrder(TreeNode* root) {
268+
vector<vector<int>> ans;
269+
if (!root) return ans;
270+
map<int, vector<int>> d;
271+
queue<pair<TreeNode*, int>> q{{{root, 0}}};
272+
while (!q.empty()) {
273+
for (int n = q.size(); n; --n) {
274+
auto p = q.front();
275+
q.pop();
276+
root = p.first;
277+
int offset = p.second;
278+
d[offset].push_back(root->val);
279+
if (root->left) q.push({root->left, offset - 1});
280+
if (root->right) q.push({root->right, offset + 1});
281+
}
282+
}
283+
for (auto& [_, v] : d) {
284+
ans.push_back(v);
285+
}
286+
return ans;
287+
}
288+
};
289+
```
290+
291+
### **Go**
292+
293+
```go
294+
/**
295+
* Definition for a binary tree node.
296+
* type TreeNode struct {
297+
* Val int
298+
* Left *TreeNode
299+
* Right *TreeNode
300+
* }
301+
*/
302+
func verticalOrder(root *TreeNode) [][]int {
303+
d := map[int][][]int{}
304+
var dfs func(*TreeNode, int, int)
305+
dfs = func(root *TreeNode, depth, offset int) {
306+
if root == nil {
307+
return
308+
}
309+
d[offset] = append(d[offset], []int{depth, root.Val})
310+
dfs(root.Left, depth+1, offset-1)
311+
dfs(root.Right, depth+1, offset+1)
312+
}
313+
dfs(root, 0, 0)
314+
idx := []int{}
315+
for i := range d {
316+
idx = append(idx, i)
317+
}
318+
sort.Ints(idx)
319+
ans := [][]int{}
320+
for _, i := range idx {
321+
v := d[i]
322+
sort.SliceStable(v, func(i, j int) bool { return v[i][0] < v[j][0] })
323+
t := []int{}
324+
for _, x := range v {
325+
t = append(t, x[1])
326+
}
327+
ans = append(ans, t)
328+
}
329+
return ans
330+
}
331+
```
332+
333+
```go
334+
/**
335+
* Definition for a binary tree node.
336+
* type TreeNode struct {
337+
* Val int
338+
* Left *TreeNode
339+
* Right *TreeNode
340+
* }
341+
*/
342+
func verticalOrder(root *TreeNode) [][]int {
343+
ans := [][]int{}
344+
if root == nil {
345+
return ans
346+
}
347+
d := map[int][]int{}
348+
q := []pair{pair{root, 0}}
349+
for len(q) > 0 {
350+
for n := len(q); n > 0; n-- {
351+
p := q[0]
352+
q = q[1:]
353+
root = p.node
354+
offset := p.offset
355+
d[offset] = append(d[offset], root.Val)
356+
if root.Left != nil {
357+
q = append(q, pair{root.Left, offset - 1})
358+
}
359+
if root.Right != nil {
360+
q = append(q, pair{root.Right, offset + 1})
361+
}
362+
}
363+
}
364+
idx := []int{}
365+
for i := range d {
366+
idx = append(idx, i)
367+
}
368+
sort.Ints(idx)
369+
for _, i := range idx {
370+
ans = append(ans, d[i])
371+
}
372+
return ans
373+
}
374+
375+
type pair struct {
376+
node *TreeNode
377+
offset int
129378
}
130379
```
131380

0 commit comments

Comments
 (0)