Skip to content

Commit cfa1c8a

Browse files
committed
feat: add solutions to lc problem: No.0987
1 parent 10f89f6 commit cfa1c8a

File tree

7 files changed

+428
-170
lines changed

7 files changed

+428
-170
lines changed

solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README.md

+147-57
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,13 @@
6262

6363
## 解法
6464

65-
### 方法一
65+
### 方法一:DFS + 排序
66+
67+
我们设计一个函数 $dfs(root, i, j)$,其中 $i$ 和 $j$ 表示当前节点的行和列。我们可以通过深度优先搜索的方式,将节点的行和列信息记录下来,存储在一个数组或列表 $nodes$ 中,然后对 $nodes$ 按照列、行、值的顺序进行排序。
68+
69+
接着,我们遍历 $nodes$,将相同列的节点值放到同一个列表中,最后返回这些列表。
70+
71+
时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。
6672

6773
<!-- tabs:start -->
6874

@@ -74,60 +80,157 @@
7480
# self.left = left
7581
# self.right = right
7682
class Solution:
77-
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
78-
def dfs(root, i, j):
83+
def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
84+
def dfs(root: Optional[TreeNode], i: int, j: int):
7985
if root is None:
8086
return
81-
nodes.append((i, j, root.val))
87+
nodes.append((j, i, root.val))
8288
dfs(root.left, i + 1, j - 1)
8389
dfs(root.right, i + 1, j + 1)
8490

8591
nodes = []
8692
dfs(root, 0, 0)
87-
nodes.sort(key=lambda x: (x[1], x[0], x[2]))
93+
nodes.sort()
8894
ans = []
8995
prev = -2000
90-
for i, j, v in nodes:
96+
for j, _, val in nodes:
9197
if prev != j:
9298
ans.append([])
9399
prev = j
94-
ans[-1].append(v)
100+
ans[-1].append(val)
95101
return ans
96102
```
97103

98104
```java
105+
/**
106+
* Definition for a binary tree node.
107+
* public class TreeNode {
108+
* int val;
109+
* TreeNode left;
110+
* TreeNode right;
111+
* TreeNode() {}
112+
* TreeNode(int val) { this.val = val; }
113+
* TreeNode(int val, TreeNode left, TreeNode right) {
114+
* this.val = val;
115+
* this.left = left;
116+
* this.right = right;
117+
* }
118+
* }
119+
*/
99120
class Solution {
121+
private List<int[]> nodes = new ArrayList<>();
122+
100123
public List<List<Integer>> verticalTraversal(TreeNode root) {
101-
List<int[]> list = new ArrayList<>();
102-
dfs(root, 0, 0, list);
103-
list.sort(new Comparator<int[]>() {
104-
@Override
105-
public int compare(int[] o1, int[] o2) {
106-
if (o1[0] != o2[0]) return Integer.compare(o1[0], o2[0]);
107-
if (o1[1] != o2[1]) return Integer.compare(o2[1], o1[1]);
108-
return Integer.compare(o1[2], o2[2]);
124+
dfs(root, 0, 0);
125+
Collections.sort(nodes, (a, b) -> {
126+
if (a[0] != b[0]) {
127+
return Integer.compare(a[0], b[0]);
109128
}
129+
if (a[1] != b[1]) {
130+
return Integer.compare(a[1], b[1]);
131+
}
132+
return Integer.compare(a[2], b[2]);
110133
});
111-
List<List<Integer>> res = new ArrayList<>();
112-
int preX = 1;
113-
for (int[] cur : list) {
114-
if (preX != cur[0]) {
115-
res.add(new ArrayList<>());
116-
preX = cur[0];
134+
List<List<Integer>> ans = new ArrayList<>();
135+
int prev = -2000;
136+
for (int[] node : nodes) {
137+
int j = node[0], val = node[2];
138+
if (prev != j) {
139+
ans.add(new ArrayList<>());
140+
prev = j;
117141
}
118-
res.get(res.size() - 1).add(cur[2]);
142+
ans.get(ans.size() - 1).add(val);
119143
}
120-
return res;
144+
145+
return ans;
121146
}
122147

123-
private void dfs(TreeNode root, int x, int y, List<int[]> list) {
148+
private void dfs(TreeNode root, int i, int j) {
124149
if (root == null) {
125150
return;
126151
}
127-
list.add(new int[] {x, y, root.val});
128-
dfs(root.left, x - 1, y - 1, list);
129-
dfs(root.right, x + 1, y - 1, list);
152+
nodes.add(new int[] {j, i, root.val});
153+
dfs(root.left, i + 1, j - 1);
154+
dfs(root.right, i + 1, j + 1);
155+
}
156+
}
157+
```
158+
159+
```cpp
160+
/**
161+
* Definition for a binary tree node.
162+
* struct TreeNode {
163+
* int val;
164+
* TreeNode *left;
165+
* TreeNode *right;
166+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
167+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
168+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
169+
* };
170+
*/
171+
class Solution {
172+
public:
173+
vector<vector<int>> verticalTraversal(TreeNode* root) {
174+
vector<tuple<int, int, int>> nodes;
175+
function<void(TreeNode*, int, int)> dfs = [&](TreeNode* root, int i, int j) {
176+
if (!root) {
177+
return;
178+
}
179+
nodes.emplace_back(j, i, root->val);
180+
dfs(root->left, i + 1, j - 1);
181+
dfs(root->right, i + 1, j + 1);
182+
};
183+
dfs(root, 0, 0);
184+
sort(nodes.begin(), nodes.end());
185+
vector<vector<int>> ans;
186+
int prev = -2000;
187+
for (auto [j, _, val] : nodes) {
188+
if (j != prev) {
189+
prev = j;
190+
ans.emplace_back();
191+
}
192+
ans.back().push_back(val);
193+
}
194+
return ans;
130195
}
196+
};
197+
```
198+
199+
```go
200+
/**
201+
* Definition for a binary tree node.
202+
* type TreeNode struct {
203+
* Val int
204+
* Left *TreeNode
205+
* Right *TreeNode
206+
* }
207+
*/
208+
func verticalTraversal(root *TreeNode) (ans [][]int) {
209+
nodes := [][3]int{}
210+
var dfs func(*TreeNode, int, int)
211+
dfs = func(root *TreeNode, i, j int) {
212+
if root == nil {
213+
return
214+
}
215+
nodes = append(nodes, [3]int{j, i, root.Val})
216+
dfs(root.Left, i+1, j-1)
217+
dfs(root.Right, i+1, j+1)
218+
}
219+
dfs(root, 0, 0)
220+
sort.Slice(nodes, func(i, j int) bool {
221+
a, b := nodes[i], nodes[j]
222+
return a[0] < b[0] || a[0] == b[0] && (a[1] < b[1] || a[1] == b[1] && a[2] < b[2])
223+
})
224+
prev := -2000
225+
for _, node := range nodes {
226+
j, val := node[0], node[2]
227+
if j != prev {
228+
ans = append(ans, nil)
229+
prev = j
230+
}
231+
ans[len(ans)-1] = append(ans[len(ans)-1], val)
232+
}
233+
return
131234
}
132235
```
133236

@@ -147,41 +250,28 @@ class Solution {
147250
*/
148251

149252
function verticalTraversal(root: TreeNode | null): number[][] {
150-
let solution = [];
151-
dfs(root, 0, 0, solution);
152-
// 优先依据i=2排序, 然后依据i=1排序
153-
solution.sort(compare);
154-
let ans = [];
155-
let pre = Number.MIN_SAFE_INTEGER;
156-
for (let node of solution) {
157-
const [val, , idx] = node;
158-
if (idx != pre) {
253+
const nodes: [number, number, number][] = [];
254+
const dfs = (root: TreeNode | null, i: number, j: number) => {
255+
if (!root) {
256+
return;
257+
}
258+
nodes.push([j, i, root.val]);
259+
dfs(root.left, i + 1, j - 1);
260+
dfs(root.right, i + 1, j + 1);
261+
};
262+
dfs(root, 0, 0);
263+
nodes.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
264+
const ans: number[][] = [];
265+
let prev = -2000;
266+
for (const [j, _, val] of nodes) {
267+
if (j !== prev) {
268+
prev = j;
159269
ans.push([]);
160-
pre = idx;
161270
}
162-
ans[ans.length - 1].push(val);
271+
ans.at(-1)!.push(val);
163272
}
164273
return ans;
165274
}
166-
167-
function compare(a: Array<number>, b: Array<number>) {
168-
const [a0, a1, a2] = a,
169-
[b0, b1, b2] = b;
170-
if (a2 == b2) {
171-
if (a1 == b1) {
172-
return a0 - b0;
173-
}
174-
return a1 - b1;
175-
}
176-
return a2 - b2;
177-
}
178-
179-
function dfs(root: TreeNode | null, depth: number, idx: number, solution: Array<Array<number>>) {
180-
if (!root) return;
181-
solution.push([root.val, depth, idx]);
182-
dfs(root.left, depth + 1, idx - 1, solution);
183-
dfs(root.right, depth + 1, idx + 1, solution);
184-
}
185275
```
186276

187277
<!-- tabs:end -->

0 commit comments

Comments
 (0)