当前位置: 代码迷 >> 综合 >> leetcode 1026. Maximum Difference Between Node and Ancestor
  详细解决方案

leetcode 1026. Maximum Difference Between Node and Ancestor

热度:92   发布时间:2024-01-16 17:56:06.0

leetcode 1026. Maximum Difference Between Node and Ancestor

题意:求一颗二叉树的一条链中的最大差值。

思路:找到每一条链,再找这条链中最大差值。

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:int maxAncestorDiff(TreeNode* root) {ans = 0;vector<int> now;dfs(root,now);return ans;}void dfs(TreeNode* root,vector<int>& now){if(root == nullptr){int min_val = 100010;int max_val = -1;for(int i =0 ;i<now.size();i++){min_val = min(min_val,now[i]);max_val = max(max_val,now[i]);}ans = max(ans,max_val-min_val);return ;}now.push_back(root->val);dfs(root->left,now);dfs(root->right,now);now.pop_back();}
private:int ans;
};

 

  相关解决方案