考虑到只能计算祖先之间的节点差而不能计算兄弟之间的节点差,所以思考使用dfs来解决该题。
/*** 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 {int ans=-1;void dfs(TreeNode* node,int max_val,int min_val){if(node==nullptr){return ;}min_val=min(min_val,node->val);max_val=max(max_val,node->val);ans=max(ans,max_val-min_val);dfs(node->left,max_val,min_val);dfs(node->right,max_val,min_val);}
public:int maxAncestorDiff(TreeNode* root) {dfs(root,root->val,root->val);return ans;}
};