Algo-Sim › Binary Trees & BST
Vertical Order Traversal of a Binary Tree
Hard · Binary Trees & BST · step through it in Java, Python and C++ on your own input
Give each node (column, row) coordinates, sort by column, row and value, then group the sorted list by column.
Problem
The root of a binary tree is at column 0, row 0; a node’s left child is one column left and one row down, its right child one column right and one row down. Return the values column by column from left to right, each column top to bottom, with nodes in the same row and column ordered by value.
Constraints
- 1 ≤ number of nodes ≤ 1000
- 0 ≤ Node.val ≤ 1000
Edge cases to test
- Two nodes at the same row and column: sort by value
- One node
- A skewed tree
Follow-up questions
- Why sort on three keys?
- The task orders by column, then row, then value; that tie-break is what separates LC 987 from LC 314.
- What is the cost?
- O(n log n) for the sort. Without the value tie-break, BFS by column with a min/max column range is O(n).
Solution
Java
public List<List<Integer>> verticalTraversal(TreeNode root) {
List<int[]> cells = new ArrayList<>();
place(root, 0, 0, cells);
// Left to right by column, then top to bottom, then the smaller value.
cells.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] != b[1] ? a[1] - b[1] : a[2] - b[2]);
List<List<Integer>> columns = new ArrayList<>();
int last = Integer.MIN_VALUE;
for (int[] c : cells) {
if (c[0] != last) {
columns.add(new ArrayList<>());
last = c[0];
}
columns.get(columns.size() - 1).add(c[2]);
}
return columns;
}
private void place(TreeNode node, int col, int row, List<int[]> cells) {
if (node == null) return;
cells.add(new int[] {col, row, node.val});
place(node.left, col - 1, row + 1, cells);
place(node.right, col + 1, row + 1, cells);
}Python
def vertical_traversal(root):
cells = []
place(root, 0, 0, cells)
# Left to right by column, then top to bottom, then the smaller value.
cells.sort()
columns, last = [], None
for col, row, val in cells:
if col != last:
columns.append([])
last = col
columns[-1].append(val)
return columns
def place(node, col, row, cells):
if not node:
return
cells.append((col, row, node.val))
place(node.left, col - 1, row + 1, cells)
place(node.right, col + 1, row + 1, cells)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode *root) {
vector<array<int, 3>> cells;
place(root, 0, 0, cells);
// Left to right by column, then top to bottom, then the smaller value.
sort(cells.begin(), cells.end());
vector<vector<int>> columns;
int last = INT_MIN;
for (auto &c : cells) {
if (c[0] != last) {
columns.push_back({});
last = c[0];
}
columns.back().push_back(c[2]);
}
return columns;
}
private:
void place(TreeNode *node, int col, int row, vector<array<int, 3>> &cells) {
if (node == nullptr)
return;
cells.push_back({col, row, node->val});
place(node->left, col - 1, row + 1, cells);
place(node->right, col + 1, row + 1, cells);
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)