LeetCode 987. 二叉树的垂序遍历

难度:困难。
标签:二叉树,深度优先搜索,广度优先搜索,哈希表。

使用哈希表来记录col,row和val的信息,然后可以使用深搜或广搜来得到这些信息,之后需要对得到的信息进行排序。

正确解法:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {

    static bool cmp(pair<int, int>& a, pair<int, int>& b){
        if(a.first == b.first){
            return a.second < b.second;
        }
        return a.first < b.first;
    }

public:
    vector<vector<int>> verticalTraversal(TreeNode* root) {
        vector<vector<int>> ans;
        
        // map<col, vector<row, val>>
        map<int, vector<pair<int, int>>> maps;
        queue<TreeNode*> node_que;
        queue<pair<int, int>> index_que;
        node_que.push(root);
        index_que.push({0, 0});
        while(!node_que.empty()){
            int size = node_que.size();

            for(int i = 0; i < size; ++i){
                TreeNode* cur = node_que.front();
                node_que.pop();
                auto pair = index_que.front();
                index_que.pop();
                int row = pair.first, col = pair.second;
                maps[col].push_back({row, cur->val});
                if(cur->left != nullptr){
                    node_que.push(cur->left);
                    index_que.push({row + 1, col - 1});
                }
                if(cur->right != nullptr){
                    node_que.push(cur->right);
                    index_que.push({row + 1, col + 1});
                }
            }
        }

        for(auto it = maps.begin(); it != maps.end(); it++){
            // cout << (*it).first << endl;
            sort((*it).second.begin(), (*it).second.end(), cmp);
            vector<int> temp;
            for(auto& p:(*it).second){
                temp.emplace_back(p.second);
            }
            ans.emplace_back(temp);
        }
        return ans;
    }
};

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值