Posted on

Description

Submission

/**
 * 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 {
    int ret;

    int dfs(TreeNode* root) {
        if(root == nullptr) return 0;

        int cur = 0;
        int diff = 0;
        if(root->left) {
            int tmp = dfs(root->left);
            cur += tmp;
            diff += tmp;
        }
        if(root->right) {
            int tmp = dfs(root->right);
            cur += tmp;
            diff -= tmp;
        }
        ret += abs(diff);
        cur += root->val;
        return cur;
    }
public:
    int findTilt(TreeNode* root) {
        ret = 0;
        dfs(root);
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *