zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    cookie和session。
    K3cloud Web API对接---单据保存接口(有源单)
    K3 wise kis 防火墙设置
    新单序时簿插件
    mssqlserver中排序规则冲突的问题解决
    读取金蝶图片
    金蝶wise委外订单关闭简述
    存储过程加锁
    判断存储过程是否存在
    解除死锁
  • 原文地址:https://www.cnblogs.com/RDaneelOlivaw/p/10366976.html
Copyright © 2011-2022 走看看