|
2 | 2 | * @Author: LetMeFly |
3 | 3 | * @Date: 2024-02-13 11:03:59 |
4 | 4 | * @LastEditors: LetMeFly |
5 | | - * @LastEditTime: 2024-02-13 11:10:24 |
| 5 | + * @LastEditTime: 2024-02-13 11:16:19 |
6 | 6 | */ |
7 | 7 | #ifdef _WIN32 |
8 | 8 | #include "_[1,2]toVector.h" |
|
19 | 19 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
20 | 20 | * }; |
21 | 21 | */ |
| 22 | +typedef pair<TreeNode*, pair<int, int>> NodeInfo; |
| 23 | + |
22 | 24 | class Solution { |
23 | 25 | public: |
24 | 26 | 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; |
28 | 30 | while (q.size()) { |
29 | | - pair<TreeNode*, int> thisNode = q.front(); |
| 31 | + NodeInfo thisNode = q.front(); |
30 | 32 | q.pop(); |
31 | 33 | v.push_back(thisNode); |
32 | 34 | 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}}); |
34 | 36 | } |
35 | 37 | 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}}); |
37 | 39 | } |
38 | 40 | } |
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; |
40 | 49 | return a.second == b.second ? a.first->val < b.first->val : a.second < b.second; |
41 | 50 | }); |
42 | 51 | 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; |
47 | 56 | ans.push_back({}); |
48 | 57 | } |
49 | 58 | ans.back().push_back(a.first->val); |
|
0 commit comments