314. 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 1:

Input: [3,9,20,null,null,15,7]

   3
  /\
 /  \
 9  20
    /\
   /  \
  15   7 

Output:

[
  [9],
  [3,15],
  [20],
  [7]
]

Examples 2:

Input: [3,9,8,4,0,1,7]

     3
    /\
   /  \
   9   8
  /\  /\
 /  \/  \
 4  01   7 

Output:

[
  [4],
  [9],
  [3,0,1],
  [8],
  [7]
]

Examples 3:

Input: [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5)

     3
    /\
   /  \
   9   8
  /\  /\
 /  \/  \
 4  01   7
    /\
   /  \
   5   2

Output:

[
  [4],
  [9,5],
  [3,0,1],
  [8,2],
  [7]
]

題目要求從上到下,然後col by col,想到用level order traversal為主體來掃描,搭配使用treemap來記錄同個col上的所有節點值。一開始root的col值定為0,往左就是減1,往右就是加1,掃描時每個節點會有各自的col值,把該節點本身的val存入map中相應的col值中。最後再把map掃過一遍把所有垂直掃描順序加入要返回的2D vector中。

vector<vector<int>> verticalOrder(TreeNode* root) { // time: O(n); space: O(n)
    vector<vector<int> > res;
    if (!root) return res;
    map<int, vector<int> > m;
    queue<pair<int, TreeNode*> > q;
    q.push({0, root});
    while (!q.empty()) {
        auto t = q.front(); q.pop();
        m[t.first].push_back(t.second->val);
        if (t.second->left) 
            q.push({t.first - 1, t.second->left});
        if (t.second->right) 
            q.push({t.first + 1, t.second->right});
    }
    for (auto& a : m) {
        res.push_back(a.second);
    }
    return res;
}

Last updated

Was this helpful?