Given a binary tree, return all of its node values grouped by diagonal.
A diagonal is defined by the path from any node towards its right child. The root is on diagonal 0. Moving to a right child keeps the node on the same diagonal, while moving to a left child increases the diagonal level by 1.
Return a list of lists where the inner list at index d contains the values on diagonal d.
Function Signature
def diagonal_traversal(tree: List[Optional[int]]) -> List[List[int]]:
Rules
-
tree
is the level-order encoding of the tree: values level by level, left to right, with
None
for a missing child. Trailing
None
values may be omitted.
-
The outer list is ordered by diagonal number, starting at 0. No inner list is empty.
-
Within a diagonal, values appear in preorder, the order in which a traversal that visits a node, then its left subtree, then its right subtree reaches them. In the first two examples this reads top to bottom along each diagonal. The third example shows a deeper node that comes first.
Constraints
-
The number of nodes is between 1 and 10^4.
-
-100 <= Node.val <= 100
Examples
Input: tree = [8,3,10,1,6,None,14,None,None,4,7,13]
Output: [[8,10,14],[3,6,7,13],[1,4]]
Diagonal 0 is the right spine 8, 10, 14; diagonal 1 is the path 3, 6, 7 (3 is the left child of 8, then right children) followed by 13, the left child of 14; diagonal 2 holds 1 and 4, the left children of 3 and 6.
Input: tree = [1,2,3,4,5,6,7]
Output: [[1,3,7],[2,5,6],[4]]
The right spine 1, 3, 7 is diagonal 0. Diagonal 1 has 2, its right child 5, and 6 (the left child of 3), and diagonal 2 has only 4.
Input: tree = [1,2,3,None,4,6,None,None,5]
Output: [[1,3],[2,4,5,6]]
Here 2 has right child 4, 4 has right child 5, and 3 has left child 6, so 2, 4, 5 and 6 are all on diagonal 1. Preorder visits all of 2's subtree, including 5 at depth 3, before it reaches 6 at depth 2, so 5 comes before 6.