本文主要是介绍leetcode 1026. Maximum Difference Between Node and Ancestor,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;
};
这篇关于leetcode 1026. Maximum Difference Between Node and Ancestor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!