LeetCode 314: Binary Tree Vertical Order Traversal Solution
Master LeetCode problem 314 (Binary Tree Vertical Order Traversal), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
314. Binary Tree Vertical Order Traversal
Problem Explanation
Explanation:
To perform a vertical order traversal of a binary tree, we can use a TreeMap (or HashMap with a sorting mechanism) to store nodes based on their horizontal distance from the root. We can do a level order traversal of the tree while keeping track of the horizontal distance of each node.
- Start with the root node and horizontal distance as 0.
- Use a queue to perform level order traversal while updating the horizontal distance of each node.
- Maintain a TreeMap to store nodes based on their horizontal distance.
- After traversing the tree, extract the nodes from the TreeMap in sorted order of horizontal distance to get the vertical order traversal.
Time Complexity: O(n log n) where n is the number of nodes in the binary tree. Space Complexity: O(n) for the TreeMap and the queue.
:
Solution Code
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
TreeMap<Integer, List<Integer>> map = new TreeMap<>();
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> hd = new LinkedList<>();
queue.offer(root);
hd.offer(0);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int col = hd.poll();
if (!map.containsKey(col)) {
map.put(col, new ArrayList<>());
}
map.get(col).add(node.val);
if (node.left != null) {
queue.offer(node.left);
hd.offer(col - 1);
}
if (node.right != null) {
queue.offer(node.right);
hd.offer(col + 1);
}
}
for (List<Integer> list : map.values()) {
result.add(list);
}
return result;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 314 (Binary Tree Vertical Order Traversal)?
This page provides optimized solutions for LeetCode problem 314 (Binary Tree Vertical Order Traversal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 314 (Binary Tree Vertical Order Traversal)?
The time complexity for LeetCode 314 (Binary Tree Vertical Order Traversal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 314 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 314 in Java, C++, or Python.