C++ Recursive O(N) Time O(1) Space


  • 0
    M
    class Solution {
    public:
        tuple<int, int, int> MinMaxDiff(TreeNode const * root) {
            if (!root) return {INT_MIN / 2, INT_MAX / 2, INT_MAX / 2};
            auto resl = MinMaxDiff(root->left), resr = MinMaxDiff(root->right);
            return {!root->left ? root->val : get<0>(resl), !root->right ? root->val : get<1>(resr),
                min(min(abs(get<1>(resl) - root->val), abs(get<0>(resr) - root->val)), min(get<2>(resl), get<2>(resr)))};
        }
        int getMinimumDifference(TreeNode* root) {
            return get<2>(MinMaxDiff(root));
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.