您的位置:首页 > 其它

Leetcode Binary Tree Vertical Order Traversal

2016-02-29 07:15 274 查看

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  DFS tree