题目链接:https://leetcode.com/problems/find-largest-value-in-each-tree-row/?tab=Description
题意:找每层的最大值。
直接dfs扔map里
1 class Solution { 2 public: 3 int sz; 4 map<int, int> ret; 5 void dfs(TreeNode* p, int d) { 6 sz = max(sz, d); 7 if(ret.find(d) == ret.end()) ret[d] = p->val; 8 else ret[d] = max(ret[d], p->val); 9 if(p->left) dfs(p->left, d+1); 10 if(p->right) dfs(p->right, d+1); 11 } 12 vector<int> largestValues(TreeNode* root) { 13 ret.clear(); 14 sz = -1; 15 if(root == NULL) return vector<int>(); 16 dfs(root, 0); 17 vector<int> v; 18 for(int i = 0; i <= sz; i++) v.push_back(ret[i]); 19 return v; 20 } 21 };
时间: 2024-11-09 20:03:08