/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
map<int, int> mp;
void dfs(TreeNode* root, int depth){
if(!root) return;
if(mp.find(depth) == mp.end()){
mp[depth] = root->val;
}
else{
if(root->val > mp[depth]) mp[depth] = root->val;
}
dfs(root->left, depth + 1);
dfs(root->right, depth + 1);
}
vector<int> res;
void fun(TreeNode* root, int depth){
if(!root) return;
if(depth == res.size()){
res.push_back(root->val);
}
else{
res[depth] = max(res[depth], root->val);
}
fun(root->left, depth+ 1);
fun(root->right, depth + 1);
}
vector<int> largestValues(TreeNode* root) {
fun(root, 0);
return res;
}
};
二叉树在每个树行中找出最大值 深度优先搜索
猜你喜欢
转载自blog.csdn.net/qq_24624539/article/details/108613676
今日推荐
周排行