Skip to content

Commit 64e1523

Browse files
committed
v1: error 排序方式错误
题看错了,同一列先从上到下排序,同一深度再按节点值的从小到大排序。
1 parent 34bc76c commit 64e1523

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* @Author: LetMeFly
3+
* @Date: 2024-02-13 11:03:59
4+
* @LastEditors: LetMeFly
5+
* @LastEditTime: 2024-02-13 11:10:24
6+
*/
7+
#ifdef _WIN32
8+
#include "_[1,2]toVector.h"
9+
#endif
10+
11+
/**
12+
* Definition for a binary tree node.
13+
* struct TreeNode {
14+
* int val;
15+
* TreeNode *left;
16+
* TreeNode *right;
17+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
18+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
19+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
20+
* };
21+
*/
22+
class Solution {
23+
public:
24+
vector<vector<int>> verticalTraversal(TreeNode* root) {
25+
queue<pair<TreeNode*, int>> q; // [<node, col>, ...
26+
q.push({root, 0});
27+
vector<pair<TreeNode*, int>> v;
28+
while (q.size()) {
29+
pair<TreeNode*, int> thisNode = q.front();
30+
q.pop();
31+
v.push_back(thisNode);
32+
if (thisNode.first->left) {
33+
q.push({thisNode.first->left, thisNode.second - 1});
34+
}
35+
if (thisNode.first->right) {
36+
q.push({thisNode.first->right, thisNode.second + 1});
37+
}
38+
}
39+
sort(v.begin(), v.end(), [&](const pair<TreeNode*, int>& a, const pair<TreeNode*, int>& b) {
40+
return a.second == b.second ? a.first->val < b.first->val : a.second < b.second;
41+
});
42+
vector<vector<int>> ans;
43+
int lastLayer = 1000000;
44+
for (pair<TreeNode*, int>& a : v) {
45+
if (a.second != lastLayer) {
46+
lastLayer = a.second;
47+
ans.push_back({});
48+
}
49+
ans.back().push_back(a.first->val);
50+
}
51+
return ans;
52+
}
53+
};

0 commit comments

Comments
 (0)