雙重遞歸
時間複雜度:
/**
* 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);
}
};