Mode of a Ternary Search Tree
Problem statement
A ternary search tree is encoded by a node table nodes. Row i is [value, leftIndex, middleIndex, rightIndex], row 0 is the root, and -1 means that a child is absent.
- Every node in a left subtree has a smaller value than its parent.
- Every node in a middle subtree has the same value as its parent.
- Every node in a right subtree has a larger value than its parent.
Return the mode: the value that occurs most often. If several values have the same highest frequency, return the smallest one.
Function
ternaryTreeMode(nodes: int[][]) → intExamples
Example 1
nodes = [[5,1,2,3],[3,-1,-1,-1],[5,-1,4,-1],[8,-1,-1,-1],[5,-1,-1,-1]]return = 5The value 5 occurs three times.
Example 2
nodes = [[2,1,2,3],[1,-1,-1,-1],[2,-1,-1,-1],[3,-1,-1,-1]]return = 2The root value occurs twice.
Example 3
nodes = [[7,-1,-1,-1]]return = 7A one-node tree has that node's value as its mode.
Constraints
1 <= nodes.length <= 200000.- Each row has exactly four integers.
- Every nonnegative child index is valid, every node is reachable exactly once from row
0, and the stated ternary-search-tree invariant holds.