Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

打卡 #1

Open
Yukibei opened this issue Apr 25, 2024 · 0 comments
Open

打卡 #1

Yukibei opened this issue Apr 25, 2024 · 0 comments

Comments

@Yukibei
Copy link

Yukibei commented Apr 25, 2024

class Solution {
public:
vector<vector> verticalTraversal(TreeNode root) {
vector<tuple<int, int, int>> data;
function<void(TreeNode
, int, int)> dfs = [&](TreeNode *node, int row, int col) {
if (node == nullptr) {
return;
}
data.emplace_back(col, row, node->val);
dfs(node->left, row + 1, col - 1);
dfs(node->right, row + 1, col + 1);
};
dfs(root, 0, 0);

    vector<vector<int>> ans;
    ranges::sort(data);
    int last_col = INT_MIN;
    for (auto &[col, _, val]: data) {
        if (col != last_col) {
            last_col = col;
            ans.push_back({});
        }
        ans.back().push_back(val);
    }
    return ans;
}

};


时间复杂度:O(nlogn),其中 nnn 为二叉树的节点个数。瓶颈在排序上。
空间复杂度:O(n)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant