Skip to main content
Brief plain-text explanation of code.
Source Link

My solution, along with a description of the TreeNode struct, is as follows. The main idea is to have a textbook-looking in-order traversal along with a visitor that builds the in-order array. Kind of expected this pattern to make the in-order traversal subroutine more generic. Finally, I find the minimum difference using the build in-order array.

My solution, along with a description of the TreeNode struct, is as follows.

My solution, along with a description of the TreeNode struct, is as follows. The main idea is to have a textbook-looking in-order traversal along with a visitor that builds the in-order array. Kind of expected this pattern to make the in-order traversal subroutine more generic. Finally, I find the minimum difference using the build in-order array.

Source Link

leetcode 530. In-order traversal of a binary search tree (C++17)

Given a binary search tree, the problem requires calculating the minimum absolute difference between any two keys in the tree. Given the binary search property, the minimum difference must be between in-order neighbors.

I am basically a C++ beginner and this was my attempt at writing "idiomatic" and readable C++17. I am looking for feedback regarding where my code falls short in this aspect.

My solution, along with a description of the TreeNode struct, is as follows.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    template <class Visitor>
    void inorder_traversal(TreeNode *root, Visitor visit) {
        if (root->left != nullptr) {
            inorder_traversal(root->left, visit);
        }
        visit(root->val);
        if (root->right != nullptr) {
            inorder_traversal(root->right, visit);
        }
        return;
    }
public:
    int getMinimumDifference(TreeNode* root) {
        using T = decltype(root->val);
        vector<T> inorder;
        auto visit = [&](T val) {
            inorder.push_back(val);
            return;
        };
        inorder_traversal(root, visit);
        adjacent_difference(inorder.begin(), inorder.end(), inorder.begin());
        auto cmp = [](T a, T b) {
            return abs(a) < abs(b);
        };
        return *min_element(inorder.begin()+1, inorder.end(), cmp);
    }
};

Optionally, is it possible to make this more performant while making few compromises on readability?

Some notes regarding the leetcode platform:

  • the solution class was already given as a template.
  • most standard library headers are included by default along with using namespace std;