Leetcode Binary Tree Vertical Order Traversal

Problem

Solution

关键点是想到怎样把每个点投影的横坐标上的位置表示出来 : 就是把root当做0 , 向左减1,向右加1
写出来是这样

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    void helper(TreeNode* root, int coord, map<int, vector<int>>& mp){
        if(!root) return;
        mp[coord].push_back(root->val);
        
        helper(root->left, coord - 1, mp);
        helper(root->right, coord + 1, mp);
    }
public:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        map<int, vector<int>> mp;
        helper(root, 0, mp);
        
        vector<vector<int>> rst;
        for( auto it = mp.begin(); it != mp.end(); it++){
            rst.push_back(it->second);
        }
        return rst;
    }
};

没通过,有一个bug 
       5
  1        6
     3   
  2    4

就不能过关,因为先到 4, 将其坐标定位1,后来到了6,又发现1,这样顺序就成了 4, 6 而不是 6, 4

修改如下 :
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 struct VerNode {
     VerNode( int d, int v) : depth(d), val(v){}
     
     int depth;
     int val;
 };
 
 bool cmp (const VerNode& n1, const VerNode& n2) {
     return n1.depth < n2.depth;
 }
 
class Solution {
    void helper(TreeNode* root, int coord, int depth, map<int, vector<VerNode>>& mp){
        if(!root) return;
        
        VerNode vn (depth, root->val);
        mp[coord].push_back(vn);
        
        helper(root->left, coord - 1, depth + 1, mp);
        helper(root->right, coord + 1,depth + 1, mp);
    }
public:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        map<int, vector<VerNode>> mp;
        helper(root, 0, 0, mp);
        
        vector<vector<int>> rst;
        for( auto it = mp.begin(); it != mp.end(); it++){
            vector<VerNode> tempVN = it->second;
            sort(tempVN.begin(), tempVN.end(), cmp);
            vector<int> temp;
            for( auto vn : tempVN){
                temp.push_back(vn.val);
            }
            rst.push_back(temp);
        }
        return rst;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值