Vertical Order Traversal of a Binary Tree
Updated
Problem statement
Given the root of a binary tree, return its vertical traversal.
Place the root at row 0, column 0. A left child is at (row + 1, column - 1), and a right child is at (row + 1, column + 1).
Return columns from the smallest to the largest column. Within a column, order nodes by row from top to bottom; if multiple nodes share both row and column, order those nodes by value ascending.
Function
verticalTraversal(root: TreeNode) → List<List<Integer>>Examples
Example 1
root = [3,9,20,null,null,15,7]return = [[9],[3,15],[20],[7]]The four occupied columns are returned from leftmost to rightmost, with node 15 below the root in column zero.
Example 2
root = [1,2,3,4,5,6,7]return = [[4],[2],[1,5,6],[3],[7]]Nodes 5 and 6 share row two and column zero, so value order places 5 first.
Example 3
root = [1,2,3,4,6,5,7]return = [[4],[2],[1,5,6],[3],[7]]Even though traversal reaches 6 before 5, their shared coordinate is sorted by value.
Constraints
- The tree contains between
1and1000nodes. 0 <= Node.val <= 1000.
More Tokopedia interview questions
- Validate Binary Search TreeONSITE INTERVIEW · Seen Aug 2021
- Kth Largest Element in an ArrayONSITE INTERVIEW · Seen Jul 2021
- Online Stock SpanONSITE INTERVIEW · Seen Jul 2021
- Interleaving StringPHONE SCREEN · Seen Jul 2021
- Delete Node in a BSTPHONE SCREEN · Seen Jul 2021
- Rotate ImagePHONE SCREEN · Seen Jul 2021
Similar questions at other companies
- Vertical Order Traversal of a Binary TreeBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Find All Paths for a Name in a File SystemThe Walt Disney Company · PHONE SCREENThe Walt Disney Company interview questions
- Serialize and Deserialize a Binary TreeAmazon · ONSITE INTERVIEW
- Recursive Display SortFigma · PHONE SCREEN · ONSITE INTERVIEWFigma interview questions
- Diameter of Binary TreeeBay · ONSITE INTERVIEWeBay interview questions
- Delete Nodes and Return Forest RootsGoogle · ONSITE INTERVIEWGoogle interview questions
- Merge N-Ary Trees by KeyLinkedIn · PHONE SCREEN · ONSITE INTERVIEWLinkedIn interview questions
- Filesystem Hash TreeCursor · PHONE SCREEN · ONSITE INTERVIEWCursor interview questions
- Aggregate Machine TopologyOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions
- Diameter of an Acyclic Undirected GraphSalesforce · ONSITE INTERVIEWSalesforce interview questions