332. Binary Tree Vertical Order Traversal

Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., 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.

Example 1:

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

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

Explanantion:

  • Node 3 is at column 0, 9 is at column -1, and 20 is at column 1.
  • 15 is at column 0 and 7 is at column 2.

Sorting column-wise, we get [[9], [3,15], [20], [7]].

Example 2:

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

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

Explanantion:

Nodes are assigned columns as follows:

  • 3 at column 0, 9 at -1, 8 at 1.
  • 4 at -2, 0 at 0, 1 at 0, 7 at 2.

Sorting by column, the order is [[4], [9], [3,0,1], [8], [7]].

Now Your Turn!

Pick the correct output for the given input

Input: root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* 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:
vector<vector<int>> verticalOrder(TreeNode* root) {
// Your code goes here
}
};
Test Case

Input:

Nums