[LeetCode314]Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples:
Given binary tree [3,9,20,null,null,15,7],
        3
       / \
      9  20
      /   \
     15   7
return its vertical order traversal as:
    [
      [9],
      [3,15],
      [20],
      [7]
    ]
Given binary tree [3,9,20,4,5,2,7],
    _3_
   /   \
  9    20
 / \   / \
4   5 2   7
return its vertical order traversal as:
    [
      [4],
      [9],
      [3,5,2],
      [20],
      [7]
    ]
Hide Company Tags Facebook
Hide Tags Hash Table
Hide Similar Problems (E) Binary Tree Level Order Traversal

这题一眼就可以看出: 对于current root, 它和 root->left->right and root->left->right 在一个vector 里。我看出这个以后就再也看不出别的了(苦笑。。

看了别人的实现方法,很好玩~BFS + hashmap。
如果current root 的index 是idx: let the index of left node be idx-1 and index of right node be idx+1 then the index of root->left->right is also idx!!!(same with root->right->left)

/**
 * 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 {
public:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        map<int, vector<int>> mp;
        queue<pair<int, TreeNode*>> q;
        vector<vector<int>> res;
        if(!root) return res;
        q.push(make_pair(0,root));
        while(!q.empty()){
            int sz = q.size();
            for(int i = 0; i<sz; ++i){
                TreeNode* cur = q.front().second;
                int idx = q.front().first;
                q.pop();
                mp[idx].push_back(cur->val);
                if(cur->left) q.push(make_pair(idx-1, cur->left));
                if(cur->right) q.push(make_pair(idx+1,cur->right));
            }
        }
        for(auto m : mp){
            res.push_back(m.second);
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章