7-liner C++ Post-order Traversal (no global variable)

  • 0

    Note that during post-order traversal, keep the sum of all nodes in a subtree for next recursion.

        int findTilt(TreeNode* r) {
            int sum;
            return tilt(r, sum);
        // find tilt and sum of all nodes
        int tilt(TreeNode* r, int& sum) {
            if (!r) return sum = 0;
            int lsum, rsum;
            int res = tilt(r->left, lsum) + tilt(r->right, rsum) + abs(lsum - rsum);
            sum = lsum + rsum + r->val;
            return res;

Log in to reply

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