LeetCode 1026. 節點與其祖先之間的最大差值(三種時間複雜度)

雙重遞歸
時間複雜度:O(n2)O(n^2)

/**
 * 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);
    }
};

優化:
每一個節點只會被訪問一次,但是每次訪問一個節點,要和它到根節點的所有的節點的值進行比較。
時間複雜度:O(nh)O(n*h)
不過在最壞情況下,仍然蛻化爲O(n2)O(n^2)

/**
 * 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();
    }
};

但只要分析一下,對每一個節點,其實並不需要和它的祖先節點都進行比較—— 只要和它的祖先節點中值最大的和最小的比較一下就可以了。
時間複雜度:
O(n)O(n)

/**
 * 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);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章