题解 | #每条路径的最大值#
每条路径的最大值
https://www.nowcoder.com/practice/9489b95288a248e3951f668b5d780031
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector
*/
vector<int> findMaxValues(TreeNode* root) {
// write code here
vector<int> res;
if(!root){
return res;
}
PreOrder(root,root->val,res);
return res;
}
void PreOrder(TreeNode* root, int &max_val, vector<int> &res){
if(root==nullptr)
return;
int temp_val = max_val;
if(root->val > max_val){
max_val = root->val;
}
if(root->left == nullptr && root->right == nullptr){
res.emplace_back(max_val);
max_val = temp_val;
}
PreOrder(root->left, max_val, res);
PreOrder(root->right, max_val, res);
}
};

查看2道真题和解析