Share my simple short c++ code using BFS


  • 0
    O
    class Solution {
    public:
        vector<vector<int>> verticalOrder(TreeNode* root) {
            vector<vector<int> > ans;
            if (root == NULL) return ans;
            map<int, vector<int> > rec;
            queue<pair<TreeNode*, int> > Q;
            Q.push(make_pair(root, 0));
            while (!Q.empty()) {
                auto cur = Q.front(); Q.pop();
                rec[cur.second].push_back(cur.first->val);
                if (cur.first->left != NULL) Q.push(make_pair(cur.first->left, cur.second + 1));
                if (cur.first->right != NULL) Q.push(make_pair(cur.first->right, cur.second - 1));
            }
            for (auto it = rec.rbegin(); it != rec.rend(); it++) ans.push_back(it->second);
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.