987. Vertical Order Traversal of a Binary Tree LeetCode Solution
In this guide, you will get 987. Vertical Order Traversal of a Binary Tree LeetCode Solution with the best time and space complexity. The solution to Vertical Order Traversal of a Binary Tree problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Vertical Order Traversal of a Binary Tree solution in C++
- Vertical Order Traversal of a Binary Tree solution in Java
- Vertical Order Traversal of a Binary Tree solution in Python
- Additional Resources

Problem Statement of Vertical Order Traversal of a Binary Tree
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.
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.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 1000
Complexity Analysis
- Time Complexity: O(n\log n/k) = O(n\log n), where k = \text{width(tree)}
- Space Complexity: O(n)
987. Vertical Order Traversal of a Binary Tree LeetCode Solution in C++
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<vector<int>> ans;
map<int, multiset<pair<int, int>>> xToSortedPairs; // {x: {(-y, val)}}
dfs(root, 0, 0, xToSortedPairs);
for (const auto& [_, pairs] : xToSortedPairs) {
vector<int> vals;
for (const pair<int, int>& pair : pairs)
vals.push_back(pair.second);
ans.push_back(vals);
}
return ans;
}
private:
void dfs(TreeNode* root, int x, int y,
map<int, multiset<pair<int, int>>>& xToSortedPairs) {
if (root == nullptr)
return;
xToSortedPairs[x].emplace(y, root->val);
dfs(root->left, x - 1, y + 1, xToSortedPairs);
dfs(root->right, x + 1, y + 1, xToSortedPairs);
}
};
/* code provided by PROGIEZ */
987. Vertical Order Traversal of a Binary Tree LeetCode Solution in Java
class Solution {
public List<List<Integer>> verticalTraversal(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
TreeMap<Integer, List<int[]>> xToSortedPairs = new TreeMap<>(); // {x: {(-y, val)}}
dfs(root, 0, 0, xToSortedPairs);
for (List<int[]> pairs : xToSortedPairs.values()) {
Collections.sort(
pairs,
(a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));
List<Integer> vals = new ArrayList<>();
for (int[] pair : pairs)
vals.add(pair[1]);
ans.add(vals);
}
return ans;
}
private void dfs(TreeNode root, int x, int y, TreeMap<Integer, List<int[]>> xToSortedPairs) {
if (root == null)
return;
xToSortedPairs.putIfAbsent(x, new ArrayList<>());
xToSortedPairs.get(x).add(new int[] {y, root.val});
dfs(root.left, x - 1, y + 1, xToSortedPairs);
dfs(root.right, x + 1, y + 1, xToSortedPairs);
}
}
// code provided by PROGIEZ
987. Vertical Order Traversal of a Binary Tree LeetCode Solution in Python
class Solution:
def verticalTraversal(self, root: TreeNode | None) -> list[list[int]]:
ans = []
xToNodes = collections.defaultdict(list)
def dfs(node: TreeNode | None, x: int, y: int) -> None:
if not node:
return
xToNodes[x].append((-y, node.val))
dfs(node.left, x - 1, y - 1)
dfs(node.right, x + 1, y - 1)
dfs(root, 0, 0)
for _, nodes in sorted(xToNodes.items(), key=lambda x: x[0]):
ans.append([val for _, val in sorted(nodes)])
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.