[leetcode] Vertical Order Traversal of a Binary Tree

1. Traverse the binary tree, store {x,y,val} for every node in records;

2. Sort the records of {x,y,val} for all nodes by increasing x, decreasing y, and increasing val order;

3. Traverse the sorted records, for elements that have same x, put their vals in a vector one by one then push the vector in the answer to return;

struct x_y_val {
    int x;
    int y;
    int val;
    x_y_val(int _x, int _y, int _val):x(_x),y(_y),val(_val) {}
};

bool cmp (x_y_val a, x_y_val b) {
    if (a.x<b.x)
        return true;
    if (a.x==b.x&&a.y>b.y)
        return true;
    if (a.x==b.x&&a.y==b.y&&a.val<b.val)
        return true;
    return false;
}
class Solution {
public:
    //need to consider y, not only x.
    void mark_x_y(TreeNode* root, int x, int y, vector<x_y_val>& records) {
        if (root==NULL)
            return;
        records.push_back(x_y_val(x,y, root->val));
        mark_x_y(root->left, x-1, y-1, records);
        mark_x_y(root->right, x+1, y-1, records);
    }
    vector<vector<int>> verticalTraversal(TreeNode* root) {
        vector<vector<int>> answer;
        if (root==NULL)
            return answer;
        vector<x_y_val> records;
        mark_x_y(root, 0,0, records);
        sort(records.begin(), records.end(), cmp);
        vector<int> temp;
        int last_x=records[0].x;
        for (auto current:records) {
            if (current.x!=last_x) {
                answer.push_back(temp);
                temp.clear();
                last_x=current.x;
            }
            temp.push_back(current.val);
        }
        answer.push_back(temp);
        return answer;
    }
};

wow, i know it's poor though.

posted @ 2019-02-12 20:29  丹尼尔奥利瓦  阅读(230)  评论(0编辑  收藏  举报