Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

Return the vertical order traversal of the binary tree.

&nbsp;
Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.

Example 2:

Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
          1 is at the top, so it comes first.
          5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.


Example 3:

Input: root = [1,2,3,4,6,5,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.


&nbsp;
Constraints:


	The number of nodes in the tree is in the range [1, 1000].
	0 &lt;= Node.val &lt;= 1000


# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
    def verticalTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        q = [(0, 0, root)]
        l = []
        while q:
            col, row, node = q.pop()
            l.append((col, row, node.val))
            if node.left:
                q.append((col-1, row+1, node.left))
            if node.right:
                q.append((col+1, row+1, node.right))
        l.sort()
        print(l)
        ans = []
        ans.append([l[0][-1]])
        for i in range(1, len(l)):
            if l[i][0] > l[i-1][0]:
                ans.append([l[i][-1]])
            else:
                ans[-1].append(l[i][-1])
        return ans
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {

    private static class MNode {
        TreeNode Node;
        int hDist;
        int level;
        MNode(TreeNode node, int hd, int l) {
            Node = node;
            hDist = hd;
            level = l;
        }
    }

    public List<List<Integer>> verticalTraversal(TreeNode root) {
        Map<Integer, PriorityQueue<MNode>> map = new TreeMap<>();
        Queue<MNode> q = new LinkedList<>();

        q.add(new MNode(root, 0, 0));

        while(!q.isEmpty()) {

            MNode curr = q.poll();
            if(map.containsKey(curr.hDist))
                  map.get(curr.hDist).add(curr);

            else {
                PriorityQueue<MNode> pq = new PriorityQueue<>
                    ((a,b) -> (a.level == b.level)? a.Node.val - b.Node.val: a.level - b.level);
                pq.add(curr);
                map.put(curr.hDist, pq);
            }

            if(curr.Node.left != null)
                q.add(new MNode(curr.Node.left, curr.hDist -1, curr.level + 1));

            if(curr.Node.right != null)
                q.add(new MNode(curr.Node.right, curr.hDist +1, curr.level + 1));
        }

        List<List<Integer>> ans = new ArrayList<>();
        for(Integer key: map.keySet()) {
            List<Integer> temp = new ArrayList<>();
            while(!map.get(key).isEmpty()) { temp.add(map.get(key).poll().Node.val); }
            ans.add(new ArrayList<>(temp));
        }

        return ans;

    }

}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 * int val;
 * TreeNode *left;
 * TreeNode *right;
 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

    // hd - horizontal distance
    // vertical order traversal starts from least hd to highest hd
    // on moving left hd decreases by 1, on moving right it increases by 1

    // should do level order traversal to get the nodes with same hd in correct order

    vector<vector<int>> verticalTraversal(TreeNode* root) {
        map<int,vector<int>> mp;
        queue<pair<TreeNode*,int>> q;
        q.push({root,0});
        while(!q.empty()){
            int sz = q.size();
            map<int,multiset<int>> temp;
            for(int i=0;i<sz;i++){
                auto pr = q.front();
                q.pop();
                temp[pr.second].insert(pr.first->val);
                if(pr.first->left != NULL){
                    q.push({pr.first->left,pr.second-1});
                }
                if(pr.first->right != NULL){
                    q.push({pr.first->right,pr.second+1});
                }
            }
            for(auto pr:temp){
                    for(auto val:pr.second){
                        mp[pr.first].push_back(val);
                    }
                }
        }
        vector<vector<int>> ans;
        for(auto pr:mp){
            vector<int> temp;
            for(auto val:pr.second){
                temp.push_back(val);
            }
            ans.push_back(temp);
        }
        return ans;
    }
};
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 * this.val = (val===undefined ? 0 : val)
 * this.left = (left===undefined ? null : left)
 * this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var verticalTraversal = function(root) {
    let ans = [];
    let l = 0, ri = 0, mi = 0;
    const preOrder = (r = root, mid = 0, d = 0) => {
        if(!r) return ;

        if(mid == 0) {
            if(ans.length < mi + 1) ans.push([]);
            ans[mi].push({v: r.val, d});
        } else if(mid < 0) {
           if(mid < l) {
               l = mid;
               mi++;
               ans.unshift([{v: r.val, d}]);
           } else {
               let idx = mi + mid;
               ans[idx].push({v: r.val, d});
           }
        } else {
            if(mid > ri) {
                ri = mid;
                ans.push([{v: r.val, d}]);
            } else {
                let idx = mi + mid;
                ans[idx].push({v: r.val, d});
            }
        }

        preOrder(r.left, mid - 1, d + 1);
        preOrder(r.right, mid + 1, d + 1);
    }
    preOrder();
    const sortByDepthOrVal = (a, b) => {
        if(a.d == b.d) return a.v - b.v;
        return a.d - b.d;
    }
    ans = ans.map(col => col.sort(sortByDepthOrVal).map(a => a.v));
    return ans;
};
Vertical Order Traversal of a Binary Tree