Skip to content

Commit 6f33a8b

Browse files
committed
v2: AC, 这次和2021年7月的代码相差就很大了
当时 大括号在另一行、没有手动空格、没有使用__[1,2]toVector.h、**还是竞赛思维** 并且当时是:最多1000列,最多往左1000,最多往右1000。第0列存到v[1000],v[y]存放所有第y列的节点。列处理上相当于是桶排序,对于每一列先按深度后按大小排序,一列一列地加入到答案数组中。
1 parent 64e1523 commit 6f33a8b

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

Codes/0987-vertical-order-traversal-of-a-binary-tree_20240213.cpp

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* @Author: LetMeFly
33
* @Date: 2024-02-13 11:03:59
44
* @LastEditors: LetMeFly
5-
* @LastEditTime: 2024-02-13 11:10:24
5+
* @LastEditTime: 2024-02-13 11:16:19
66
*/
77
#ifdef _WIN32
88
#include "_[1,2]toVector.h"
@@ -19,31 +19,40 @@
1919
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
2020
* };
2121
*/
22+
typedef pair<TreeNode*, pair<int, int>> NodeInfo;
23+
2224
class Solution {
2325
public:
2426
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;
27+
queue<NodeInfo> q; // [<node, <col, height>>, ...
28+
q.push({root, {0, 1}});
29+
vector<NodeInfo> v;
2830
while (q.size()) {
29-
pair<TreeNode*, int> thisNode = q.front();
31+
NodeInfo thisNode = q.front();
3032
q.pop();
3133
v.push_back(thisNode);
3234
if (thisNode.first->left) {
33-
q.push({thisNode.first->left, thisNode.second - 1});
35+
q.push({thisNode.first->left, {thisNode.second.first - 1, thisNode.second.second + 1}});
3436
}
3537
if (thisNode.first->right) {
36-
q.push({thisNode.first->right, thisNode.second + 1});
38+
q.push({thisNode.first->right, {thisNode.second.first + 1, thisNode.second.second + 1}});
3739
}
3840
}
39-
sort(v.begin(), v.end(), [&](const pair<TreeNode*, int>& a, const pair<TreeNode*, int>& b) {
41+
sort(v.begin(), v.end(), [&](const NodeInfo& a, const NodeInfo& b) {
42+
// if (a.second.first != b.second.first) { // not same col
43+
// return a.second.first < b.second.first;
44+
// }
45+
// if (a.second.second != b.second.second) { // same col, different row
46+
// return a.second.second < b.second.second;
47+
// }
48+
// return a.first->val < b.first->val;
4049
return a.second == b.second ? a.first->val < b.first->val : a.second < b.second;
4150
});
4251
vector<vector<int>> ans;
43-
int lastLayer = 1000000;
44-
for (pair<TreeNode*, int>& a : v) {
45-
if (a.second != lastLayer) {
46-
lastLayer = a.second;
52+
int lastCol = 1000000;
53+
for (NodeInfo& a : v) {
54+
if (a.second.first != lastCol) {
55+
lastCol = a.second.first;
4756
ans.push_back({});
4857
}
4958
ans.back().push_back(a.first->val);

0 commit comments

Comments
 (0)