[InterviewBit] Diagonal Traversal

Diagonal Traversal

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* node, unordered_map<int, vector<int>>& mp, vector<int>& seq, int y, int x) {
if(!node) return;
int hash = y - x;
if(!mp.count(hash)) seq.push_back(hash);
mp[hash].push_back(node->val);
dfs(node->left, mp, seq, y + 1, x - 1);
dfs(node->right, mp, seq, y + 1, x + 1);
}
vector<int> Solution::solve(TreeNode* A) {
unordered_map<int, vector<int>> mp;
vector<int> seq;
dfs(A,mp,seq,0,0);

vector<int> res;
for(auto s : seq) {
for(auto v : mp[s]) {
res.push_back(v);
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/27/PS/interviewbit/diagonal-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.