[LeetCode]515 Find Largest Value in Each Tree Row(dfs)
Posted tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]515 Find Largest Value in Each Tree Row(dfs)相关的知识,希望对你有一定的参考价值。
题目链接: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 };
以上是关于[LeetCode]515 Find Largest Value in Each Tree Row(dfs)的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-515-Find Largest Value in Each Tree Row]
[LeetCode]515 Find Largest Value in Each Tree Row(dfs)
(BFS 二叉树) leetcode 515. Find Largest Value in Each Tree Row
leetcode515- Find Largest Value in Each Tree Row- medium