双重递归
时间复杂度:
/**
* 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 ans = 0 ;
int maxAncestorDiff(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root){
if(!root){
return;
}
helper(root,root->val);
dfs(root->left);
dfs(root->right);
}
void helper(TreeNode* root,int val){
if(!root){
return;
}
ans = max(ans,abs(root->val-val));
helper(root->left,val);
helper(root->right,val);
}
};
优化:
每一个节点只会被访问一次,但是每次访问一个节点,要和它到根节点的所有的节点的值进行比较。
时间复杂度:
不过在最坏情况下,仍然蜕化为
/**
* 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 ans = 0 ;
int maxAncestorDiff(TreeNode* root) {
vector<int> vis;
dfs(root,vis);
return ans;
}
void dfs(TreeNode* root,vector<int>&vis){
if(!root){
return;
}
for(int x:vis){
ans = max(ans,abs(root->val-x));
}
vis.push_back(root->val);
dfs(root->left,vis);
dfs(root->right,vis);
vis.pop_back();
}
};
但只要分析一下,对每一个节点,其实并不需要和它的祖先节点都进行比较—— 只要和它的祖先节点中值最大的和最小的比较一下就可以了。
时间复杂度:
/**
* 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 ans = 0 ;
int maxAncestorDiff(TreeNode* root) {
dfs(root,root->val,root->val);
return ans;
}
void dfs(TreeNode* root,int maxV,int minV){
if(!root) return ;
maxV = max(maxV,root->val);
minV = min(minV,root->val);
ans = max(ans,max(abs(root->val-maxV),abs(root->val-minV)));
dfs(root->left,maxV,minV);
dfs(root->right,maxV,minV);
}
};