C++ in order traversal with global variable


  • 0
    B

    if you do not want do use global variable, you can define variable in getMinimumDifference() and overload this function with more arguments

    /**
     * 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:
        TreeNode * last;
        long ans = INT_MAX * 3;
    
        int getMinimumDifference(TreeNode* root) {
            if(!root) return ans;
            getMinimumDifference(root -> left);
            if(!last) last = root;
            else
            {
                long dif = root -> val;
                dif -= last -> val;
                if(dif < 0) dif = -dif;
                if(ans > dif) ans = dif;
                last = root;
            }
            getMinimumDifference(root -> right);
            return ans;
        }
    };

Log in to reply
 

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