1) Diagonal 1 contains [1, 2, 3]
2) Diagonal 2 contains [4, 5, 7, 6]
3) Diagonal 3 contains [8, 9]
NOTE:
The order in the output matters like for Example:
6 and 7 belong to same diagonal i.e diagonal 2 but as 7 comes before 6 in pre-order traversal so 7 will be added to answer array first.
So concantenate all the array as return it as a single one.
Final output: [1, 2, 3, 4, 5, 7, 6, 8, 9]
Explanation 2:
1) Diagonal 1 contains [11, 12, 13]
2) Diagonal 2 contains [20, 15, 17, 16]
3) Diagonal 2 contains [1, 2, 22, 34]
So concantenate all the array as return it as a single one.
Final output: [11, 12, 13, 20, 15, 17, 16, 1, 2, 22, 34]
public class Solution {
HashMap<Integer, List<Integer>> map;
int size;
public void diagonalPrint(TreeNode root, int level) {
if (root == null)
return;
size++;
map.computeIfAbsent(level, k -> new ArrayList<>()).add(root.val);
diagonalPrint(root.left, level - 1);
diagonalPrint(root.right, level);
}
public int[] solve(TreeNode root) {
size = 0;
map = new HashMap<>();
diagonalPrint(root, 0);
int[] ans = new int[size];
int index = 0;
for (int level = 0; level > -map.size(); level--)
for (int x : map.get(level))
ans[index++] = x;
return ans;
}
}