#987
Hard Algorithms Vertical order traversal of a binary tree
Hash Table Tree Depth-First Search Breadth-First Search Sorting Binary Tree
53.3% acceptance
Feb 27, 2026
8598
4391
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.
Solution
Rust
Time O(n log n)
Space O(n)
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn vertical_traversal(root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut nodes: Vec<(i32, i32, i32)> = Vec::new(); // (col, row, val)
fn dfs(node: &Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, col: i32, row: i32, nodes: &mut Vec<(i32, i32, i32)>) {
if let Some(n) = node {
let n = n.borrow();
nodes.push((col, row, n.val));
dfs(&n.left, col - 1, row + 1, nodes);
dfs(&n.right, col + 1, row + 1, nodes);
}
}
dfs(&root, 0, 0, &mut nodes);
nodes.sort();
let mut res: Vec<Vec<i32>> = Vec::new();
let mut prev_col = i32::MIN;
for (col, _, val) in nodes {
if col != prev_col { res.push(Vec::new()); prev_col = col; }
res.last_mut().unwrap().push(val);
}
res
}
}