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
|
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; }
|