码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Binary Tree Vertical Order"

时间:2015-12-15 13:59:32      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

BFS + HashTable

class Solution 
{
    int maxl, minl;
    unordered_map<int, vector<int>> hm;
public:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        maxl = INT_MIN;
        minl = INT_MAX;
        
        typedef pair<TreeNode*, int> Rec;
        queue<Rec> q;
        if (root)
        {
            q.push(Rec(root, 0));
        }
        while (!q.empty())
        {
            Rec curr = q.front(); q.pop();
            int l = curr.second;
            maxl = max(maxl, l);
            minl = min(minl, l);

            TreeNode *tmp = curr.first;
            hm[l].push_back(tmp->val);

            if (tmp->left)
            {
                q.push(Rec(tmp->left, l - 1));
            }
            if (tmp->right)
            {
                q.push(Rec(tmp->right, l + 1));
            }
        }

        vector<vector<int>> ret;
        for (int i = minl; i <= maxl; i++)
        {
            if (hm[i].size() == 0) continue;
            ret.push_back(hm[i]);
        }

        return ret;
    }
};

LeetCode "Binary Tree Vertical Order"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5047820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!