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

[leetcode] Vertical Order Traversal of a Binary Tree

时间:2019-02-12 21:45:45      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:sorted   tree   push   als   roo   node   vertica   turn   style   

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.

[leetcode] Vertical Order Traversal of a Binary Tree

标签:sorted   tree   push   als   roo   node   vertica   turn   style   

原文地址:https://www.cnblogs.com/RDaneelOlivaw/p/10366976.html

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